为什么链表合并函数在Java中无法正常工作?

huangapple go评论155阅读模式
英文:

Why is the link list merge function not working in Java?

问题

问题出现在合并函数的 'while(m.next!=null)' 部分。它抛出了一个 "NullPointerException"。

public class Linked {

    node ptr1;
    node ptr2;

    void merge()
    {
        node m=ptr1;

        while(m.next!=null)
            m=m.next;
        m.next=ptr2;
    }

    void printmerged()
    {
        node m=ptr1;

        while(m.next!=null)
            System.out.print(m.data+", ");
        System.out.println(m);
    }
}
英文:

The problem arises in the merge function at 'while(m.next!=null)'. It throws a "NullPointerException".

public class Linked {

    node ptr1;
    node ptr2;

    void merge()
    {
        node m=ptr1;

        while(m.next!=null)
            m=m.next;
        m.next=ptr2;
    }

    void printmerged()
    {
        node m=ptr1;

        while(m.next!=null)
            System.out.print(m.data+", ");
        System.out.println(m);
    }
}

答案1

得分: 1

我在你的代码中添加了注释,以便向你解释正在发生的情况。

    node ptr1; // 在这里 ptr1 是空的
    node ptr2;
    
    void merge()
    {
        node m=ptr1; // 你正在将 null 赋给 m
    
        while(m.next!=null) // 你正在访问一个空对象的 "next" 属性
            m=m.next;
        m.next=ptr2;
    }

你必须实例化你的对象,否则它们将会是 null。

英文:

I added comments to your code to explain to you what's going on.

node ptr1; //ptr1 is null here
node ptr2;

void merge()
{
    node m=ptr1; //you are assigning null to m

    while(m.next!=null) //you are accessing the "next" property of a null object
        m=m.next;
    m.next=ptr2;
}

You have to instantiate your objects otherwise they are going to be null.

huangapple
  • 本文由 发表于 2020年6月5日 21:44:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/62216794.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定