Given a linked list, remove the n-th node from the end of list and return its head.
Solution: fast指针先移动n格,接着两指针同时移动,直到fast.next = null
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode slow = dummy, fast = dummy;
for (int i = 0; i < n; i++) {
fast = fast.next;
}
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummy.next;
}