所以我有一个方法可以将ListNode添加到现有的ListNode中,并且当head != null时添加到末尾时它可以工作,但是一旦head = null,它就会打印就像head为null一样。通过执行 head.getValue(),我知道它为 head 添加了值,但它仍然打印 head = null。
public static void add(ListNode <Integer> head, Integer value)
{
if (head == null)
{
head = new ListNode <Integer> (value, null);
head.setNext(null);
} else {
while (head.getNext() != null)
{
head = head.getNext();
}
head.setNext(new ListNode <Integer> (value, null));
}
}
public static void printLinkedList(ListNode <Integer> head)
{
if (head == null)
{
System.out.println();
return;
}
for(; head.getValue() != null; head = head.getNext())
{
System.out.print(head.getValue() + " ");
if(head.getNext() == null)
{
break;
}
}
System.out.println();
}
最佳答案
Java is pass-by-value 。因此,当您在 add 方法中为 head
创建一个新的对象引用时,该引用将在该方法的末尾结束,
public static void add(ListNode <Integer> head, Integer value) {
if (head == null)
{
head = new ListNode <Integer> (value, null);//creates new reference
head.setNext(null);
} else {
while (head.getNext() != null)
{
head = head.getNext();
}
head.setNext(new ListNode <Integer> (value, null));
}
}
可能的解决方案是,在方法调用本身期间初始化head
,
您的添加方法
public static void add(ListNode <Integer> head, Integer value) {
while (head.getNext() != null){
head = head.getNext();
}
head.setNext(new ListNode <Integer> (value, null));
}
通话期间
if (head == null) {
head = new ListNode <Integer> (value, null);
head.setNext(null);
}
else add(head,value);
关于java - ListNode header value 不会打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52461463/