19.Remove Nth Node From End of List

给定一个链表和一个数字n,将链表上倒数第n个节点删掉。
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.


思路:
运用双指针,第一个指针先走n步,然后两个指针一起向前走,当第一个指针走到尾的时候,第二个指针就走到了倒数第n+1个节点,然后将其指向倒数第n-1个节点即可。
注意链表只有一个节点且n=1的情况;以及链表长度为n的情况。

ListNode* removeNthFromEnd(ListNode* head, int n) {
    if (n == 0) return head;
    ListNode* res = head;
    ListNode* tmp = head;
    while (n--) tmp = tmp->next;
    if (!tmp && head->next==NULL) return NULL;//链表长为1,n=1
    if (!tmp) return head->next;//链表长为n
    while (tmp->next) {
        head = head->next;
        tmp = tmp->next;
    }
    head->next = head->next->next;
    return res;
}

Java 版:

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode res = head, tmp = head;
        while(n-- > 0) tmp = tmp.next;
        if(tmp == null) return res.next; // 防止出现n = 链表长度时,则直接去掉第一个头结点
        while(tmp.next != null){
            head = head.next;
            tmp = tmp.next;
        }
        head.next = head.next.next;
        return res;
    }
}
原文地址:https://www.cnblogs.com/luo-c/p/12913348.html