Question:
Given a linked list, remove the nth node from the end of list and return its head.
For 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.
本题难度easy,常规方法就不介绍了。我在discuss看到华人写的另一种解法,方法很不错。帖子是:My java solution, using a fast pointer,作者:传说选手。
方法:
1、fast pointer move n steps in advance
2、cur pointer and fast pointer move together
3、do the reconnection
我对其代码进行了改进:
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
//require
if(head==null)
return head;
ListNode fast=head;
ListNode fake=new ListNode(0);
fake.next=head;
//invariant
while(n>0){//move fast n steps in advance
fast=fast.next;
n--;
}
ListNode cur=fake;
while(fast!=null){
fast=fast.next;
cur=cur.next;
}
cur.next=cur.next.next;
//ensure
return fake.next;
}
}