删除链表的第N个节点
力扣刷题,怕以后忘记,记录一下解决思路
题目描述
代码
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function (head, n) {
// 指针
let i = head
let j = i
let step = 0
while (step < n && j != null) {
j = j.next
step++
}
// 判断是否删除首节点
if (j == null) {
return i.next
}
while (j.next != null) {
j = j.next
i = i.next
}
i.next = i.next.next
return head
};