java - ListNode header value 不会打印

标签 java head

所以我有一个方法可以将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/

相关文章:

javascript - 除了需要指向的网站之外,是否可以托管 Javascript 文件?

.net - 头与 WebClient?

javascript - Next.js - 如何在 <head> 内添加带有文字 onload 属性字符串值的 <link> 标记?

header - Gnuplot:每一个行为都很奇怪

java - Android: "Fatal Exception"使用 Google map 时在 URLConnection 上调用 getInputStream()

java - 在线程之间共享对象对性能有何影响?

python - 在不知道索引的情况下获取 Series 的第一个元素

java - 如何编写将 json 响应与场景大纲表进行比较的步骤定义

java - 向现有对象添加接口(interface)

Java - 修改我的 To String 方法