This is a problem from a book testing you on LinkedLists, Stacks, and Queue. The goal is to print out the desired output from this short snippet of code. I have accompanied the code with my analysis.
LinkedList<Integer> a = new LinkedList<Integer>(); Stack<Integer> s = new Stack<Integer>(); Queue<Integer> q = new LinkedList<Integer>(); a.add( 2 ); a.add( 3 ); a.add( 5 ); a.add( 7 ); The LL: a = {2, 3, 5, 7}
for ( int i : a ) { System.out.print( i + " " ); s.push( i ); q.add( i ); } print output: 2 3 5 7
The stack: s = {2, 3, 5, 7}
The queue: q = {2, 3, 5, 7}
System.out.println(); for ( int i : a ) { s.push( i ); q.add( s.pop() + 5 ); System.out.print( s.pop() + " " ); } The stack: s = {2, 3, 5, 7, 2, 3, 5, 7}
The queue: q = {2, 3, 5, 7, 12, 10, 8, 7}. This is as a result of s.pop() + 5
Print output: 7 5 3 2
System.out.println(); for ( int i : a ) { System.out.print( q.remove() + " " ); System.out.print( q.remove() + " " ); } Print output: 2 3 5 7 12 10 8 7
So in summary, my print outputs are:
2 3 5 7
7 5 3 2
2 3 5 7 12 10 8 7
The answer to this problem, however, is this:
2 3 5 7
7 5 3 2
2 3 5 7 7 8 10 12
As you can see, the results don't match in the queue printing. I redid the problem twice, but could not determine whether I did something wrong in the addition (s.pop() + 5) or in my .pop() printing. Could someone give me some insight on what I did wrong?