题目
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.
思路
为这个list定义一个头指针delNode,然后再定义一个指针指向head,让这俩指针始终保持n的距离,那delNode.next就是需要删除的节点,然后删掉就可以了,注意特别考虑要删除的节点是head的情况,要把head重新指定一下它的位置.
代码
var removeNthFromEnd = function(head, n) {
if (head == null) {
return [];
}
var delNode = new ListNode(0);
delNode.next = head;
var lastNode = head;
var dis = 1;
while (lastNode.next !== null) {
if (dis < n) {
lastNode = lastNode.next;
dis++;
}
else {
delNode = delNode.next;
lastNode = lastNode.next;
}
}
var temp = delNode.next;
delNode.next = temp.next;
if (temp == head)
head = delNode.next;
temp.next = null;
return head;
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。