19. Remove Nth Node From End of List

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.

Follow up:

Could you do this in one pass?

two pointers,快指针先走n步,然后快慢指针一起走,当快指针走到最后一个node时,慢指针指向被删除节点的前一个

注意:需要一个dummy node,因为head有可能被删除,初始时快慢指针都指向dummy node

time: O(n), space: 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) return head;
        ListNode dummy = new ListNode(0);
        ListNode p1 = dummy, p2 = dummy;
        p1.next = head;
        while(n > 0) {
            p1 = p1.next;
            n--;
        }
        while(p1.next != null) {
            p1 = p1.next;
            p2 = p2.next;
        }
        p2.next = p2.next.next;
        return dummy.next;
    }
}
原文地址:https://www.cnblogs.com/fatttcat/p/10135566.html