The answer might be obvious, however I still feel the need to ask. So I programmed a simple Linked_List for fun and training and noticed that one method that is supposed to print the elements of the list actually runs faster than the method that prints the list backward.
I kept thinking about a reason to explain this, but I kept going in circle, I would be interesting to know why.
Here is my first method (this is the simple traversing of the list)
public void list(){
Node<E> iter = head;
while(iter != null){
System.out.print(iter.getValue() + ", ");
iter = iter.getNext();
}
}
Here is the other method, it prints the list backward
public void list_inverse(){
Node<E> iter = head;
Stack<Node<E>> stack = new Stack<Node<E>>();
while(iter != null){
stack.push(iter);
iter = iter.getNext();
}
while(!stack.isEmpty()){
Node<E> tmp = stack.peek();
stack.pop();
System.out.print(tmp.getValue() + ", ");
}
}
so the idea of the second method is the go through the list and add each item to a stack. After reaching the end, I just print the element contained in the stack. So you can see, the second method was supposed to run in a longer period of time.
in the main method we have :
long startTime = System.nanoTime();
list.list();
long ElapsedTime = System.nanoTime();
System.out.println();
long startTime2 = System.nanoTime();
list.list_inverse();
long ElapsedTime2 = System.nanoTime();
the output I had :
give the number for the list, if you want to stop, write stop
1
2
3
4
5
6
7
8
9
10
stop
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, //first method
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, // second method
it has taken 8.15E-5 second for list and 5.19E-5 second for list_inverse