首页 > 解决方案 > 绘制节点的图片及其指向的位置

问题描述

我应该在输入以下代码后直观地解释四个节点是如何出现的:

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;
    }
}

从我迄今为止所做的工作来看,似乎:

这是图像这是我从调试器中引用的图像)

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

标签: javapointers

解决方案


鉴于每个Object 的Dataand为 null,让我们从您的 main 函数开始逐步了解它。(建议您对这些变量名使用 camelCase https://en.wikipedia.org/wiki/Camel_caseNextNode

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; // c.next == null. null.Data doesn't exist. 

C.Next = A; // C.Next = A; A == new Node(); no error

推荐阅读