19. Remove Nth Node From End of List(删除链表中的第n个结点)

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

方法一:双指针

删除倒数第n个点,我们首先得找到倒数第n个点才行。因为链表只能从头开始找,倒数第n个点就是正数第m-n(设链表长是m)。我让第一个指针先走n个点然后和第二个指针一起走,再走n-m个点。走到链表尾端时,第二个指针就走到倒数第n个数。

第一个循环找的是两个指针相差的个数。如果要找倒数第n个结点两个指针就相差n-1个。如果要找倒数第n个结点的前一个结点那两个指针就相差n-1个。

时间复杂度:o(n)                   空间复杂度:o(1)

/**
 * 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||n<1) return null;
        ListNode current=head;
        ListNode result=head;
        for(int i=0;i<n;i++){
            current=current.next;
        }
        if(current==null) return head.next; //说明要删除的是正数第一个数(倒数最后一个数)。
        while (current.next!=null){
            current=current.next;
            result=result.next;
        }
        result.next=result.next.next;
        return head;
    }
}

 方法二:根据链表的特点(单指针)

例如题目中给的例子:

 1->2->3->4->5 当n=5时,就是要删除倒数第五个结点,正好是正数第一个。此时当遍历完链表之后n也为0;
1->2->3->4->5 当n=2时,就是要删除倒数第2个结点,就是中间的某个结点。此时当遍历完链表之后n=-3,再从头开始遍历找到n==0时的点,此时的点是要删除的前一个点。其实可以这么理解。
删除倒数第n个结点就相当于删除正数第k-n+1个结点。第一个while 循环控制的是k+1,第二个循环控制的是n。本来是应该让它循环n次的,但是呢,这里是删除结点。所以要找到它的前一个结点
和它后一个结点连起来。所以第二个循环控制的是n-1次。
 1->2->3->4->5 当n=6时,就是删除倒数第六个结点,但是我们只有5个结点。所以直接返回就行。    
/**
 * 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||n<1) return null;
        ListNode current=head;
        while(current!=null){ 
            current=current.next;
            n--;
        }
        if(n==0){   //n为0时,正好是k==n时。就是要求删除的是第一个结点(k为链表长度)
            head=head.next;  
        }else if(n<0){  //n<0说明是删除中间的某个结点,此时要找到n=0时的点,因为这个点正好指向要删除的前一个结点
            current=head;
            while (++n!=0){
               current=current.next;
            }//n>0说明n大于链表长度。直接返回原链表就行。
            current.next=current.next.next;
        }
        return head;
    }
}
苟有恒,何必三更眠五更起;最无益,莫过一日暴十日寒。
原文地址:https://www.cnblogs.com/shaer/p/10555991.html