【问题标题】:Looping through java recursive references循环遍历java递归引用
【发布时间】:2014-08-21 14:29:27
【问题描述】:

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

  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 指向的对象。我的问题是,给定这样的递归结构,正确的循环机制是什么?我知道在链表中,不需要到达链表的末尾来执行加法。链表结构用作询问循环遍历递归结构的上下文。谢谢。

【问题讨论】:

  • 您可以随时查看java.util.LinkedList 的源代码,看看它是如何实现的。

标签: java loops recursion linked-list


【解决方案1】:

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

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

应该更改字段startItem 的唯一时间是在您第一次检查其值是否为null 时。它的引用不应更改,因为它应始终指向结构的开头。考虑将其设为 final 以强制执行此操作。

【讨论】: