题目描述:
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
代码实现:
- 常规方法,第一次遍历找到链表的长度,第二次删除对应节点。
/**
* 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) {
var preHead = new ListNode(null)
preHead.next = head
var len = 0
var first = head
while (first) {
len++
first = first.next
}
len -= n
first = preHead
while (len != 0) {
len--
first = first.next
}
first.next = first.next.next
return preHead.next
};
- 双指针法,很精妙的解法,快指针先跑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) {
var preHead = new ListNode(null)
preHead.next = head
var fast = preHead
var slow = preHead
while (n != 0) {
fast = fast.next
n--
}
while (fast.next != null) {
fast = fast.next
slow = slow.next
}
slow.next = slow.next.next
return preHead.next
};