我应该在视觉上解释输入以下代码后四个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;
}
}
到目前为止,我的工作似乎是:
以上两行给出NullPointer错误是否正常?我的猜测还接近图片吗?感谢您的帮助
鉴于每个Data
对象的Next
和Node
为空,让我们从主函数开始逐步介绍它。 (建议您将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