• Lc19_删除链表的倒数第N个节点


    
    //给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。 
    //
    // 示例: 
    //
    // 给定一个链表: 1->2->3->4->5, 和 n = 2.
    //
    //当删除了倒数第二个节点后,链表变为 1->2->3->5.
    // 
    //
    // 说明: 
    //
    // 给定的 n 保证是有效的。 
    //
    // 进阶: 
    //
    // 你能尝试使用一趟扫描实现吗? 
    // Related Topics 链表 双指针
    
    package leetcode.editor.cn;
    
    import com.example.demo.ArrayConvertLinkedList;
    import com.example.demo.ListNode;
    
    //Java:删除链表的倒数第N个节点
    public class P19RemoveNthNodeFromEndOfList {
        public static void main(String[] args) {
            Solution solution = new P19RemoveNthNodeFromEndOfList().new Solution();
            // TO TEST
            int[] array1 = {1,2,3,4,5};
            int n =2;
            ListNode head1 = ArrayConvertLinkedList.arrayToNode(array1);
            ListNode res = solution.removeNthFromEnd(head1,n);
            ArrayConvertLinkedList.printNode(res);
        }
        //leetcode submit region begin(Prohibit modification and deletion)
    
        /**
         * Definition for singly-linked list.
         * public class ListNode {
         * int val;
         * ListNode next;
         * ListNode(int x) { val = x; }
         * }
         */
        class Solution {
            public ListNode removeNthFromEnd(ListNode head, int n) {
                if (head == null) {
                    return head;
                }
                int len = 0;
                ListNode curr = head;
                while (curr != null) {
                    len++;
                    curr = curr.next;
                }
                int delPosition = len - n - 1;
                if (delPosition==-1) {
                    head = head.next;
                    return head;
                }
                int currPosition = 0;
                ListNode curr2 = head;
                while (head != null) {
                    if (currPosition != delPosition) {
                        currPosition++;
                        curr2 = curr2.next;
                    } else {
                        curr2.next = curr2.next.next;
                        return head;
                    }
                }
                return null;
            }
        }
    //leetcode submit region end(Prohibit modification and deletion)
    
    }
    
  • 相关阅读:
    中国大概可用NTPserver地址
    ROOT android 原则。 基于(zergRush)
    Struts2他们拦截器实例定义—登陆权限验证
    引用与指针
    address_space 从哪里来
    C++ 可以多个函数声明
    linux下远程管理利器-tmux
    内核空间和用户空间的分界 PAGE_OFFSET
    io端口
    C中程序的内存分配
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/13271691.html
Copyright © 2020-2023  润新知