【发布时间】:2012-08-25 17:50:07
【问题描述】:
我是 Java 新手,我正在尝试实现一个链接列表(我确实知道为此目的存在一个列表类,但是从头开始让我了解该语言在内部是如何工作的)
在main方法中,我声明了4个节点并初始化了3个。链表的头节点设置为null。 第一次使用参数head和newNode调用add函数时,head为null,所以我初始化head并将newNode的值赋给它。 在 main 方法中,我希望 head 对象应该从 add 方法中设置新值。但是 head 仍然为空。
我希望能理解为什么会发生这种情况。
抱歉,如果代码不干净,非常感谢!
public class LinkedList
{
public void add(Node newNode, Node head)
{
if(head == null)
{
head = new Node();
head = newNode;
}
else
{
Node temp = new Node();
temp = head;
while(temp.next!=null)
{
temp = temp.next;
}
temp.next = newNode;
}
}
public void traverse(Node head)
{
Node temp = new Node();
temp = head;
System.out.println("Linked List:: ");
while(temp.next!=null);
{
System.out.println(" " + temp.data);
temp = temp.next;
}
}
public static void main(String args[])
{
Node head = null;
Node newNode = new Node(null, 5);
Node newNode2 = new Node(null, 15);
Node newNode3 = new Node(null,30);
LinkedList firstList = new LinkedList();
firstList.add(newNode,head);
// Part that I don't understand
// why is head still null here?
if(head==null)
{
System.out.println("true");
}
firstList.traverse(head);
firstList.add(newNode2,head);
firstList.traverse(head);
firstList.add(newNode3,head);
firstList.traverse(head);
}
}
public class Node
{
public Node next;
public int data;
public Node(Node next, int data)
{
this.next = next;
this.data = data;
}
public Node()
{
this.next = null;
this.data = 0;
}
}
【问题讨论】:
-
您可能会发现this post 很有趣。当您在代码顶部写
head = new Node()时,您更改了参数的本地副本,但这不会更改其在调用代码中的值。 -
您采取了哪些步骤进行调试?
标签: java null nullpointerexception linked-list