Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过java递归引用循环_Java_Loops_Recursion_Linked List - Fatal编程技术网

通过java递归引用循环

通过java递归引用循环,java,loops,recursion,linked-list,Java,Loops,Recursion,Linked List,我正在编写一个简单的链表实现和相应的触发器类,如下所示: public class Trigger { public static void main(String[] args) { LinkedList lin = new LinkedList(); lin.add(3); lin.add(4); lin.add(5); lin.display(); } } public class LinkedLis

我正在编写一个简单的链表实现和相应的触发器类,如下所示:

  public class Trigger {
    public static void main(String[] args) {
      LinkedList lin = new LinkedList();
      lin.add(3);
      lin.add(4);
      lin.add(5);
      lin.display();
    }
  }


 public class LinkedList {
      Item startItem;

      LinkedList() {
      startItem = new Item();
    }  

    public void add(Integer newValue) {
      if(startItem.value == null) {
        startItem.value = newValue;
        return;
      }

    Item tempItem = new Item();
    tempItem.value = newValue;

    while(startItem.next != null) {
     startItem = startItem.next;
    }

    startItem.next = tempItem;
   }

   public void display() {
     while(true) {
       System.out.println("\t"+ startItem.value);
       if(startItem.next == null) {
         break;
       } else {
         startItem = startItem.next;
       }  
     }
   }   

class Item {
 Integer value;
 Item next;

 Item() {
  this.value = null;
  this.next = null;
 }
}
}

问题是,只有最后两个添加被保留,而之前的添加被丢弃。这(当然)是因为我一直在更改引用startItem指向的对象。我的问题是,给定这样的递归结构,正确的循环机制是什么?我知道在链表中,不需要到达列表的末尾来执行加法。链表结构被用作询问递归结构循环的上下文。谢谢。

您的基本结构是正确的。你只需要在开始循环之前添加一行

  Item currentItem = startItem;
  while(currentItem.next != null) {
     currentItem = currentItem.next;
  }

字段
startItem
唯一应该更改的时间是在第一次检查其值是否为
null
时。它的引用永远不应该改变,因为它应该始终指向结构的开始。考虑让它<代码>最终< /代码>来执行这个。

你可以查看源代码:<代码> java .UTI.Link KEdList,看看它是如何实现的。