java - mystery about Linked_List traversing -
the answer might obvious, still feel need ask. programmed simple linked_list fun , training , noticed 1 method supposed print elements of list runs faster method prints list backward.
i kept thinking reason explain this, kept going in circle, interesting know why.
here first method (this simple traversing of list)
public void list(){ node<e> iter = head; while(iter != null){ system.out.print(iter.getvalue() + ", "); iter = iter.getnext(); } }
here other method, prints 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 idea of second method go through list , add each item stack. after reaching end, print element contained in stack. can see, second method supposed run in longer period of time.
in main method 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 had :
give number list, if want 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 has taken 8.15e-5 second list , 5.19e-5 second list_inverse
stack in java uses vector
internally. vector
uses array
, stores elements in consecutive memory locations. hence, jvm doesn't need go memory location pointed reference retrieve values. can scan next memory location , values.
i believe main reason difference in execution times first , second method. pure guesswork though ;-)
Comments
Post a Comment