绘制节点及其指向的图片

问题描述 投票:0回答:1

我应该在视觉上解释输入以下代码后四个Node的显示方式:

public class Node
{

    //These two lines are provided
    public Object Data = null;
    public Node Next = null;

    public static void main(String[] args)
    {
        Node a = new Node();
        Node b = new Node();
        Node c = new Node();
        Node d = new Node();

        //These four lines must be used
        b = a.Next;
        //c = b.Next;                //Gives NullPointer error
        //b.Data = c.Next.Data;      //Gives NullPointer error
        c.Next = a;
    }
}

到目前为止,我的工作似乎是:

  • A指向节点(不变)
  • B变成空对象
  • C的节点指向A
  • D指向节点(不变)

([This is the image这是我从调试器引用的图像)

以上两行给出NullPointer错误是否正常?我的猜测还接近图片吗?感谢您的帮助

java pointers
1个回答
1
投票

鉴于每个Data对象的NextNode为空,让我们从主函数开始逐步介绍它。 (建议您将camelCase用作这些变量名https://en.wikipedia.org/wiki/Camel_case

Node A = new Node(); 
Node B = new Node(); 
Node C = new Node(); 
Node D = new Node(); // Defines non-null A, B, C, and D Nodes

B = A.Next; // B = null; because the Next and Data of each node is null

C = B.Next; // C = (a non existent) b.next causing a null pointer error
B.Data = C.Next.Data; B.Data = c.Next.Data; // c.next == null. null.Data doesn't exist. 

C.Next = A; // C.Next = A; A == new Node(); no error
© www.soinside.com 2019 - 2024. All rights reserved.