/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ var removeNthFromEnd = function (head, n) { //当节点只有一个的情况 if (head.next === null) { head = null; return head; } //当节点只有两个,且n===1的情况 if (head.next.next === null && n === 1) { head.next.next = null; head.next = null; return head; }
//当节点只有两个,且n===2的情况 if (head.next.next === null && n === 2) { let _head = head.next; head = null; head = _head; return head; }
let prevNode; //被删除节点的上一个节点 let nextNode; //被删除节点的下一个节点 let deleteNode; //被删除节点
let firstNode = head; //可以移动的x指针节点 let pointer = head; let lastNode; //可以移动的最后一个指针节点 //查找n指针 for (let i = 0; i < n; i++) { lastNode = pointer; pointer = lastNode.next; }