Reputation: 17
i am brushing up on some programming this summer, i was doing this question as follows. 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.
Basically my method is returning the reversed order of the stack, except in the case of an odd number of numbers in the stack, i except it to at least return the sum for me, regardless of order. I am supposed to use only 1 queue My question is where am i going wrong here, why cant i sum my 2 pops. public static Stack collapse(Stack sO) {
Queue<Integer> qN = new LinkedList<Integer>();
int x1 = 0;
int x2 = 0;
while(!sO.empty())
{
qN.add(sO.pop());
}
while(!qN.isEmpty())
{
int sum = 0;
x1 = qN.remove();
if(sO.empty()){
qN.add(x1); break;
}
else{x2 = qN.remove();
sum = x1 + x2;
qN.add(sum);}
}
while(!qN.isEmpty()){
sO.push(qN.remove());
}
return sO;
bottom [7, 2, 8, 9, 4, 13, 7, 1, 9, 10] top 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:
bottom [9, 17, 17, 8, 19] top
Upvotes: 0
Views: 79
Reputation: 121
This part of code will be infinite looping:
if(sO.empty()){
qN.add(x1); break;
}
you are removing x1 from queue and again adding it back to queue.
Modify your lower while block by
while(!qN.isEmpty())
{
x1=qN.remove();
x2=qN.remove();
sO.push(x1+x2);
}
Remember:If number of elements are odd,x2 will be null for last iteration.Take care of it.
Upvotes: 1