将新元素添加到节点的末尾(Java)

时间:2014-04-06 21:24:34

标签: java list generics nodes generic-list

我无法在列表末尾添加元素。它不断添加到列表的开头。我已经在这一段时间了,只是陷入困境中。

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());

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

list = newNode;

此行会立即将您添加的节点设置为列表的开头!

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

last.setLink(newNode);
last = newNode;

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

希望这有帮助!