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.
給一個鏈表耀怜,刪除倒數第n個數字恢着,我們的策略是兩個指針,從頭開始财破,假設倒數第五個掰派,先讓一個指針走出去五個,然后兩個同時啟動左痢,當第一個到了最末尾靡羡,第二個也就到了我們最終想要的位置了。
java代碼:
public static ListNode removeNthFromEnd(ListNode head, int n) {
if (n < 1) return head;
int i = 0;
ListNode before = head;
while (i < n + 1 && before != null) {
before = before.next;
i++;
}
if(i == n+1){
ListNode after = head;
while(before!=null){
before = before.next;
after = after.next;
}
ListNode temp = after.next;
after.next = temp.next;
}else if (i == n){
ListNode tmep = head;
head = head.next;
}
return head;
}