I have an add() method for my doubly circular linked list which is supposed to add new Nodes at the end while maintaining the data structure. But when I create a doubly circular linked list and print the contents, the output is a list of the first item only.
The method is adding only the first item only.
My class makes use of DoubleNode class which is imported. DoubleNode<E>works fine.
Double node is just a node which has a getPrevious() method in addition to getNext() method.
public void add(E item){ public class DCLinkedList<E> implements SomeInterface<E>{ private int numberOfItems= 0; private DoubleNode<E> first; private DoubleNode<E> currentPosition; public DCLinkedList(){ first = null; currentPosition = first;} public void add(E item){ private DoubleNode<E> node = new DoubleNode<E>(item); if(numElements == 0){ first = node; first.setPrevious(first); first.setNext(first); numberOfItems++; currentPosition = first; } else{ node.setBack(currentPosition.getPrevious()); currentPosition.getPrevious().setNext(node); node.setNext(first); currentPosition = head; numberOfItems++; } public String toString(){ String string = ""; int i = 0; while( i < numberOfItems){ string += currentPosition.getInfo()+" "; i++; } return "{"+string.substring(0,string.length()-1)+"}"; } } //Here's what happens when I try to run the code. public static void main(String[] args){ DCLinkedList<Integer> someList = new DCLinkedList<Integer>(); someList.add(1); someList.add(2); someList.add(4); System.out.println(list.toString()); }
--- Update ---
Was in the middle of deleting post but thought some will find it useful. It turns out the problem was in my toString() method. I actually solved the problem while writing the toString() method. I saw my mistake. So, you should think about your code while posting. You might just spot the mistake and correct it.