链表实际上就是一维有序数组, 要移除倒数第N个节点, 只需做以下步骤:
- 链表指针从头移到尾
- 开始往上回去N个节点.
- 该节点即需要删除的节点.
- 找到该节点, 将上个节点的
next
值改为当前节点的next
值, 即可移除该节点.
/**
* 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) {
let curr = head
const listNodes = [ head ]
while (curr.next) {
curr = curr.next
listNodes.push(curr)
}
const { length } = listNodes
const index = length - n - 1
if (index > 0) {
listNodes[index].next = listNodes[index + 1].next
} else if (index < 0) {
return head.next
} else {
head.next = head.next.next
return head
}
return head
};