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;
};