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個位置,當第一個指針到頭時,第二個指針所指的下一個就是要刪的節點。有兩個特殊情況要注意,一個是要刪的是頭節點,一個是鏈表里就一個節點。
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
if (head === null)
return head;
if (head.next===null)
return null;
var pointer1 = head;
var pointer2 = head;
var num = 1;
while (pointer1.next!==null) {
if (num>n)
pointer2 = pointer2.next;
else
num++;
pointer1 = pointer1.next;
}
if (n === num)
return pointer2.next;
else
pointer2.next = pointer2.next.next;
return head;
};