Appearance
19. 删除链表的倒数第 N 个结点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例 1:
输入:head = [1, 2, 3, 4, 5], n = 2
输出:[1, 2, 3, 5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1, 2], n = 1
输出:[1]
提示:
链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
进阶:你能尝试使用一趟扫描实现吗?
- 来源:力扣(LeetCode)
- 链接:https://leetcode.cn/problems/remove-nth-node-from-end-of-list
javascript
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function (head, n) {
if (n === 1 && head && !head.next) {
return null
}
let pre = head,
cur = head,
i = 0
for (; pre; pre = pre.next) {
i++
}
if (i === n) {
cur = cur.next
return cur
}
const k = i - n
for (let j = 1; j < k; j++) {
cur = cur.next
}
cur.next = n === 1 ? null : cur.next.next
return head
}
var removeNthFromEnd = function (head, n) {
let temp = head,
list = [head],
i = 1
while (temp.next) {
temp = temp.next
list.push(temp)
i++
}
if (i === 1) {
return null
}
const remove = i - n
if (remove === 0) {
return head.next
}
const pre = list[remove - 1]
pre.next = pre.next.next
return head
}
var removeNthFromEnd = function (head, n) {
const newNode = new ListNode(0)
newNode.next = head
let left = newNode,
right = newNode,
i = 0
while (i <= n) {
right = right.next
i++
}
while (right) {
left = left.next
right = right.next
}
if (left && left.next) {
left.next = left.next.next
}
return newNode.next
}
// test
function ListNode(val, next) {
this.val = val === undefined ? 0 : val
this.next = next === undefined ? null : next
}
var l1 = new ListNode(1)
var lstNode1 = new ListNode(2)
var lstNode2 = new ListNode(3)
var lstNode3 = new ListNode(4)
var lstNode4 = new ListNode(5)
l1.next = lstNode1
lstNode1.next = lstNode2
lstNode2.next = lstNode3
lstNode3.next = lstNode4
console.log(removeNthFromEnd(l1, 2))