给定一个链表,删除链表的倒数第 n 个节点并返回链表的头指针
例如,
例如,
给出的链表为: , .
删除了链表的倒数第 个节点之后,链表变为.
删除了链表的倒数第 个节点之后,链表变为.
数据范围: 链表长度 ,链表中任意节点的值满足
要求:空间复杂度 ,时间复杂度
备注:
备注:
题目保证 一定是有效的
// 基于哨兵(假头节点) 节点的双指针方法 // 双指针 let removeNthFromEnd = (head, n)=>{ let fakeHead = {next: head}, p1 = fakeHead, p2 = fakeHead; while (p2 && n+1 > 0){ p2 = p2.next; n--; } while (p2){ p1 = p1.next; p2 = p2.next; } p1.next = p1.next.next; return fakeHead.next; } module.exports = { removeNthFromEnd : removeNthFromEnd };
function removeNthFromEnd( head , n ) { // write code here const map = new Map() let cur = head let i = 0 while (cur) { map.set(i, cur) i ++ cur = cur.next } const pre = map.get(i - n - 1) const next = map.get(i - n + 1) if (!pre) return head.next pre.next = next return head }
function removeNthFromEnd( head , n ) { let dummy = new ListNode(0); dummy.next = head; let length = 0; while(head){ length++; head = head.next; } let curr = dummy; for(let i =1;i<length-n+1;i++){ curr = curr.next; } curr.next = curr.next.next; return dummy.next; } module.exports = { removeNthFromEnd : removeNthFromEnd };
function removeNthFromEnd( head , n ) { // write code here if(head==null)return head let newhead = new ListNode(0) newhead.next = head head = newhead let slow = head,fast = head let i=0; while(fast){ if(i>n){ slow = slow.next } fast = fast.next i++ } slow.next = slow.next.next return newhead.next }
function removeNthFromEnd( head , n ) { // write code here //反转链表 let prev = null let cur = head const reverse = (prev,cur) =>{ while(cur){ let next = cur.next cur.next = prev prev = cur cur = next } return prev } let newHead = reverse(prev,cur) //边界处理 if(n==1) { return reverse(null, newHead.next) } //查询节点 const findNodeIndex = (curSearchTmp,n) => { let pos = 1 while(curSearchTmp &&pos !== n){ curSearchTmp = curSearchTmp.next pos++ } return curSearchTmp } let curSearch = findNodeIndex(newHead,n) //查找前一个节点 let pre = findNodeIndex(newHead,n-1) //删除节点 pre.next = curSearch.next let preNeed = null let curNeed = newHead //反转回来 return reverse(preNeed,curNeed) }2.老老实实双指针 快慢指针指向头部,快指针先走n-1,然后再同时走,快指针走到末尾的时候,慢指针指向倒数第k个节点
function removeNthFromEnd( head , n ) { // write code here let slow = head, fast = head while(n > 0){ fast = fast.next n-- } if(fast === null){ slow = slow.next return slow } while(fast.next){ slow = slow.next fast = fast.next } slow.next = slow.next.next return head }