【问题标题】:Adding a new element to the end of a Node (Java)将新元素添加到节点的末尾(Java)
【发布时间】:2014-04-06 21:24:33
【问题描述】:

我无法将元素添加到我的列表末尾。它继续添加到列表的开头。我已经有一段时间了,只是卡住了,迷路了。

public class RefUnsortedList<T> implements ListInterface<T> {

      protected int numElements;      // number of elements in this list
      protected LLNode<T> currentPos; // current position for iteration

      // set by find method
      protected boolean found;        // true if element found, else false
      protected LLNode<T> location;   // node containing element, if found
      protected LLNode<T> previous;   // node preceeding location

      protected LLNode<T> list;       // first node on the list

      public RefUnsortedList() {
        numElements = 0;
        list = null;
        currentPos = null;
      }

      public void add(T element) {
      // Adds element to this list.


        LLNode<T> newNode = new LLNode<T>(element);

        newNode.setLink(list);
        list = newNode;
        numElements++;

这是我的主要课程:

RefUnsortedList<Patient> patient1 = new RefUnsortedList<Patient>();
Patient entry;
entry = new Patient("Tam Ngo", "0848896");
patient1.add(entry);
entry = new Patient("Mike You", "0848896");
patient1.add(entry);

System.out.println(patient1.toString());

【问题讨论】:

  • 稍微思考一下你在做什么......你正在创建一个新节点,你将新节点的链接(下一个)设置为旧列表并将“第一个节点”设置为列表”到新节点。这会将节点放在列表的首位。

标签: java list generics nodes generic-list


【解决方案1】:

java中的add方法有第二个签名,可以使用:http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#add(int,E)

您可以指定要添加下一个元素的位置

【讨论】:

  • 非常感谢!我使用 ArraySortedList 的一部分来查找位置,然后将新节点设置为以前的位置。
【解决方案2】:

正如所写,您的 list 变量包含列表中的第一个节点。现在,您的 add 方法包括以下行:

list = newNode;

这一行立即将您要添加的节点设置到列表的开头!

一个可能的解决方法是维护两个指针:一个指向列表的开头(用于搜索列表),另一个指向最后一个元素,假设您将其称为last。在这种情况下,要添加节点,您可以执行以下操作:

last.setLink(newNode);
last = newNode;

这里,我们设置了从当前最后一个节点到新节点的链接,然后将新节点作为新的最后一个节点。

希望这会有所帮助!

【讨论】:

  • 我想我明白你的意思。我在课堂上学习了标题和预告片,但不确定如何将其实现到 RefUnsortedList。我对此的理解很模糊
猜你喜欢
  • 2013-02-14
  • 1970-01-01
  • 2012-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-25
  • 2015-06-14
相关资源
最近更新 更多