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