链表删除倒数第n个节点时出现Cannot Read Properties of Null错误求助
问题描述
我正在解决一道算法题,题目要求如下:
给定链表的头节点head,删除链表的倒数第n个节点并返回头节点。
我编写了函数removeNthFromEnd(head, n),接收链表头节点和n作为参数。思路是先遍历链表获取总长度,再遍历一次停在要删除节点的前一个节点(例如n=2时停在倒数第3个节点)。
遇到的问题
我能成功定位到目标节点的前一个节点,也能访问其next节点,但访问next的next节点时出现类型错误:
Line 35 in solution.js console.log(node.next.next); ^ TypeError: Cannot read properties of null (reading 'next')
我的代码
function removeNthFromEnd(head, n) { // set the current node let node = head; // Set the current count let count = 1; // Loop through the linkedlist to get the length of the linked list while (node && node.next) { // Increment the count count++; // Move to the next node node = node.next; } // Set the current node to the head node = head; // Loop though the linked list to get the last node before the deleted node for (let i = 1; i < count - n; i++) { node = node.next; } node.next = node.next.next; return head; };
已尝试的方法
用一次遍历的双指针变种算法已经实现了功能,删除节点时同样使用next = next.next的逻辑,但两次遍历的写法就会出现上述错误,应该是犯了某个低级错误但没发现。
问题分析与解决
你遇到的错误核心是两种场景未处理:
删除头节点的情况:当链表总长度
count等于n时,要删除的就是头节点。此时你的代码里count - n = 0,for循环不会执行,node仍指向head。如果链表只有1个节点,node.next是null,访问null.next就会报错;即使链表更长,直接修改head的next也不符合需求,应该直接返回head.next。删除尾节点的情况:当要删除的是最后一个节点时,
node.next就是尾节点,它的next属性为null,此时访问node.next.next等同于访问null.next,自然抛出类型错误。
修正后的代码
function removeNthFromEnd(head, n) { let node = head; let count = 1; // 遍历获取链表总长度 while (node && node.next) { count++; node = node.next; } // 特殊处理:删除头节点 if (count === n) { return head.next; } node = head; // 遍历到目标节点的前一个节点 for (let i = 1; i < count - n; i++) { node = node.next; } // 即使node.next是尾节点,node.next.next为null,赋值操作依然合法 node.next = node.next.next; return head; };
验证场景
- 链表长度为1,n=1:触发
count===n,返回head.next(即null),正确删除唯一节点。 - 链表长度为3,n=3:返回
head.next,正确删除头节点。 - 链表长度为4,n=1:遍历到倒数第2个节点,将其next设为null,正确删除尾节点。
- 链表长度为5,n=2:遍历到倒数第3个节点,将其next指向倒数第1个节点,正确删除倒数第2个节点。
内容的提问来源于stack exchange,提问作者TheInfamousGrim
相关产品推荐
相关产品推荐

