我是新来的Java和我试图实现一个链表(我知道一个列表类存在这个目的,但从头开始让我理解语言如何在内部工作)对象值null
在主要方法中,我声明4个节点并初始化3.链接列表的头节点设置为空。 第一次使用参数head和newNode调用add函数时,head为null,所以我初始化head并为它指定newNode的值。 在主要方法中,我期望头对象应该有从add方法设置的新值。但头仍然是空的。
我很感激为什么会发生这种情况。
道歉,如果代码不干净,谢谢大量!
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;
}
}
您可能会发现[这篇文章](http://stackoverflow.com/questions/40480/is-java-pass-by-reference)有趣。当您在代码的顶部写入'head = new Node()'时,您将更改参数的本地副本,但不会更改其在调用代码中的值。 – assylias
你采取了哪些步骤进行调试? –