给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
方法:使用 2 个指针:
fast
快指针提前走n+1
步slow
指针指向当前距离fast
倒数第n
个节点, 初始为head
然后, fast 、 slow 同步向前走,直到 fast.next 为 null
此时,fast 为最后一个节点,slow 就是倒数第 n+1 个节点,此时问题就变更为删除链表中的 slow 的后继节点
但存在一个问题,当链表长度为 n 时,fast 是前进不到 n+1 个节点位置的,所以此时有两种解决思路:
-
创建一个头节点 preHead ,设置 preHead.next = head ,这样就可以解决以上问题,删除倒数第 n 个节点后,返回的 preHead.next 即可
-
另外一种是,fast 快指针提前走 n 步后,判断 fast.next 是否为 null ,即 fast 是否是最后一个节点,如果是,则 head 为倒数第 n 个节点,此时问题可以简化为删除头节点;如果不是, fast = fast.next ,fast 再前进一步,slow 为倒数第 n+1 个节点,也解决了以上问题。
-
时间复杂度:O(n)
空间复杂度:O(1)
-
方法一:添加
preHead
节点
var removeNthFromEnd = function(head, n) {
let preHead = new ListNode(0)
preHead.next = head
let fast = preHead, slow = preHead
// 快先走 n+1 步
while(n--) {
fast = fast.next
}
// fast、slow 一起前进
while(fast && fast.next) {
fast = fast.next
slow = slow.next
}
slow.next = slow.next.next
return preHead.next
};
作者:user7746o
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/javascriptshan-chu-lian-biao-dao-shu-di-n-ge-jie-d/
来源:力扣(LeetCode)
- 方法二:单独处理倒数第
n
节点
var removeNthFromEnd = function(head, n) {
let fast = head, slow = head
// 快先走 n 步
while(--n) {
fast = fast.next
}
if(!fast.next) return head.next
fast = fast.next
// fast、slow 一起前进
while(fast && fast.next) {
fast = fast.next
slow = slow.next
}
slow.next = slow.next.next
return head
};
作者:user7746o
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/javascriptshan-chu-lian-biao-dao-shu-di-n-ge-jie-d/
来源:力扣(LeetCode)
- 这是双指针的简化写法,还是用双指针吧
/*
删除倒数第n个节点,我们先换取删除节点的前一个节点,然后再修改它的next指向到下一个的next就好了。
获取删除节点通过循环获取链表长度,然后计算出节点的位置,再循环得到节点。
当然如果节点是头节点,我们就直接返回head.next
*/
var removeNthFromEnd = function(head, n) {
let node = head
let count = 0
while(node) {
node = node.next
count++
}
count = count - n - 1
if(count == -1) return head.next
node = head
while(count>0) {
node = node.next
count--
}
node.next = node.next.next
return head
};
作者:a-mao-da-ma
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/shan-chu-lian-biao-de-dao-shu-di-nge-jie-dian-b-64/
来源:力扣(LeetCode)