You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

链表问题:跳过M节点后删除N节点的Java代码报NullPointerException求助

链表跳过M节点删除N节点的NullPointerException修复

你遇到的NullPointerException是因为遍历链表时未正确检查节点是否为空就访问其next属性,常见于以下两种场景:

  • 跳过M个节点时,链表剩余长度不足M,仍继续尝试访问current.next
  • 删除N个节点时,剩余节点不足N,仍持续移动指针导致访问null.next

修复后的代码实现

假设链表节点定义为:

class Node {
    int data;
    Node next;
    Node(int d) {
        data = d;
        next = null;
    }
}

修复后的完整链表实现代码:

public class LinkedList {
    Node head;

    public void skipMdeleteN(int M, int N) {
        Node current = head;
        Node temp;

        // 遍历整个链表
        while (current != null) {
            // 跳过M个节点(从第1个开始计数,循环M-1次)
            for (int i = 1; i < M && current != null; i++) {
                current = current.next;
            }

            // 如果跳过M个后已到链表末尾,直接终止
            if (current == null) {
                return;
            }

            // 定位到要删除的节点起始位置,跳过N个节点
            temp = current.next;
            for (int i = 1; i <= N && temp != null; i++) {
                temp = temp.next;
            }

            // 连接跳过M后的节点与删除N后的节点
            current.next = temp;
            // 移动current到下一轮的起始节点
            current = temp;
        }
    }

    // 辅助方法:打印链表
    public void printList() {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.data + "->");
            temp = temp.next;
        }
        System.out.println("null");
    }

    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.head = new Node(1);
        list.head.next = new Node(2);
        list.head.next.next = new Node(3);
        list.head.next.next.next = new Node(4);
        list.head.next.next.next.next = new Node(5);
        list.head.next.next.next.next.next = new Node(6);
        list.head.next.next.next.next.next.next = new Node(7);
        list.head.next.next.next.next.next.next.next = new Node(8);

        list.printList();
        list.skipMdeleteN(2, 2);
        list.printList();
    }
}

关键修复点说明

  1. 跳过M节点时的空检查:在循环中加入current != null判断,避免链表长度不足M时访问null.next
  2. 提前终止判断:跳过M个节点后立即检查current是否为null,如果是直接返回,防止后续无效操作
  3. 删除N节点时的空检查:移动temp指针时加入temp != null判断,避免剩余节点不足N时触发NPE
  4. 正确更新指针:每次操作后将current移动到temp,确保下一轮循环从正确的起始节点开始

运行上述代码,输入1->2->3->4->5->6->7->8->null,M=2,N=2,会得到预期输出1->2->5->6->null。

内容的提问来源于stack exchange,提问作者Mamik Saha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 05:37:30