Java - BJP3 Exercise 14.4: collapse Write a method collapse that takes a stack o
ID: 654564 • Letter: J
Question
Java - BJP3 Exercise 14.4: collapse
Write a method collapse that takes a stack of integers as a parameter and that collapses it by replacing each successive pair of integers with the sum of the pair. For example, suppose a stack stores these values:
The first pair should be collapsed into 9 (7 + 2), the second pair should be collapsed into 17 (8 + 9), the third pair should be collapsed into 17 (4 + 13) and so on to yield:
If the stack stores an odd number of elements, the final element is not collapsed. For example, the stack:
Would collapse into:
With the 5 at the top of the stack unchanged. You may use one queue as auxiliary storage.
Explanation / Answer
public void collapse(Stack<Integer>s)
{
Queue<Integer>q = new LinkedList<Integer>();
for(i=0;i<=s.size;i++)
q.enqueue(s.pop());
while(!q.dequeue())
s.push(q.dequeue());
while(!s.isEmpty())
q.enqueue(s.pop());
while(q.size()>1)
s.push(q.dequeue()+q.dequeue());
if(!q.isEmpty())
s.push(q.dequeue());
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.