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.
Try to do this in one pass.
翻譯 :刪除掉單鏈表倒數(shù)第N個元素浆洗,N總是有效的 荞彼,一次遍歷翠胰。
Trick 在于使用兩個指針克伊,一個P1指向開頭勾给,另一個P2指向第N個結點袋毙,二者同時向后遍歷沪摄,當P2達到TAIL時诱篷,P1也就到達了指定的結點阔拳。
PS:本來想不適用pre來保存前一個節(jié)點崭孤,單純的使用delete O(1)的方法來寫刪除的,但是這種方法只適用于所刪除的結點后面結點非空的情況糊肠。折騰了一番辨宠,還是乖乖寫了pre結點。
http://www.reibang.com/p/23e2affa80c5
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode (0);
dummy.next = head ;
ListNode pos = dummy;
ListNode pre = dummy;
int count = n ;
while(count>0)
{
pos=pos.next;
count--;
}
// 追蹤到tail ,此時head 指向的是倒數(shù)第N個結點货裹。
while(pos.next!=null)
{
head=head.next;
pos=pos.next;
pre=pre.next;
}
pre.next=head.next;
return dummy.next;
}
}