简体   繁体   English

在节点末尾添加新元素(Java)

[英]Adding a new element to the end of a Node (Java)

im having trouble adding elements to the end of my list. 我在将元素添加到列表末尾时遇到麻烦。 It keeps on adding to the beginning of the list. 它一直添加到列表的开头。 I've been at this for a while now, just stuck and lost. 我已经在这里呆了一段时间,只是陷入困境而已。

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++;

Here is my main class: 这是我的主要课程:

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

the add method in java has a second signature, which you can use: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#add(int , E) java中的add方法具有第二个签名,您可以使用它: http : //docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#add(int ,E)

You can specify where you want to add your next element 您可以指定要添加下一个元素的位置

As is written, your list variable holds the first node on the list. 如所写,您的list变量将保留list的第一个节点。 Now, your add method includes the line: 现在,您的add方法包括以下行:

list = newNode;

This line immediately sets the node you're adding to the beginning of the list! 这行代码立即将您要添加的节点设置为列表的开头!

A possible fix is to maintain two pointers: one to the beginning of the list (for searching through it) and one to the last element, let's say you call it last . 一种可能的解决方法是维护两个指针:一个指向列表的开头(用于搜索列表)和一个指向最后一个元素(假设您将其称为last In that case, to add a node you could do the following: 在这种情况下,要添加节点,您可以执行以下操作:

last.setLink(newNode);
last = newNode;

Here, we set a link from the current last node to the new node, and then make the new node the new last node. 在这里,我们设置了从当前最后一个节点到新节点的链接,然后使新节点成为新的最后节点。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM