Question

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());
Was it helpful?

Solution

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)

You can specify where you want to add your next element

OTHER TIPS

As is written, your list variable holds the first node on the list. Now, your add method includes the line:

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. 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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top