Question: Write a method called collapse that accepts a stack of integers as a parameter and that collapses it by replacing each successive pair of integers

Write a method called collapse that accepts 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, if the stack stores [7, 2, 8, 9, 4, 11, 7, 1, 42] , the first pair should be collapsed into 9 (7 + 2), the second pair should be collapsed into 17 (8 + 9), and so on. If the stack stores an odd number of elements, such as the 42 at the end of our example stack, the final element is not collapsed. So for this stack your method would yield [9, 17, 15, 8, 42]. Use one queue as auxiliary storage.

Step by Step Solution

3.38 Rating (148 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

public static void collapse Stack s Queue q n... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Building Java Programs A Back to Basics Approach Questions!