Problem
Given a linked list, remove the nth node from the end of list and return its head.
Example
Given linked list: 1->2->3->4->5->null, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5->null.
Challenge
Can you do it without getting the length of the linked list?
Note
首先建立dummy结点指向head,复制链表。
然后建立快慢指针结点fast、slow,让fast比slow先走n个结点,再让fast和slow一起走,直到fast到达链表最后一个结点。由于fast比slow快n个结点,所以slow正好在链表倒数第n+1个结点。
最后让slow指向slow.next.next,就删除了原先的slow.next———倒数第n个结点。
返回dummy.next,结束。
Solution
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null || n <= 0) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode slow = dummy, fast = dummy;
while (n-- != 0) {
fast = fast.next;
}
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用。你还可以使用@来通知其他用户。