So I have a method to add a ListNode to an existing ListNode, and it works when it adds to the end when head != null, but as soon as head = null, it prints as if head is null. Through doing head.getValue(), I know it adds value to head, but it still prints that 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();
}
答案 0 :(得分:2)
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);
答案 1 :(得分:0)
This looks like a pass-by-reference issue. Briefly, instantiating a new object is the one place when pass-by-reference does not work.
When you pass an object reference to a method, the method is getting a new pointer to the object. Operations on the object will affect both "versions" of the object because the method and global are pointing to the same object.
But if you re-initialize that pointer (with the "new" keyword) inside the method, the method's pointer is now pointing to the new object, and the original pointer outside the method is not updated.
To fix your error, you'd need to handle the "head is null" case outside the "add" method.