Reputation: 37
Greetings Stack Overflow community. I'm trying to make a function that can pop all the values in a stack, add them and then push them back. I've so far been successful in adding, subtracting, dividing and multiplying two values by just popping them twice to local variables, performing the operation and then pushing back the completed value. But to add all I would require to pop from the stack until its empty.
I've tried adding a loop to popping two values and pushing the result back. This is what I have in mind
push these numbers 1 , 2 , 3, 4 ,5
pop 5
pop 4
add 5 + 4 = 9
push 9
stack (1,2,3,4,9)
pop 9
pop 4
add 9+4 = 13
push 13
and so on. I've tried using the isEmpty function for the loop and trying to make it that it stops when one of the values is not NULL. But I have no idea how to stop or start the loop so it keeps going until its empty. Here is what I have written.
void MathStack::addAll()
{
int num = 0,num2 = 0, sum = 0;
while(!isEmpty())
{
//Pop the first two values off the stack.
pop(num);
cout << "Popping " << num << "\n";
pop(num2);
cout << "Popping " << num2 << "\n";
//Add the two values, store in sum.
sum = num + num2;
cout << "Sum is " << sum;
//Push sum back onto the stack.
push(sum);
num =0;
num2 = 0;
}
}
Any suggestions?
Upvotes: 1
Views: 8877
Reputation: 168706
There is no reason to push the intermediate sum back onto the stack. Just keep the sum in a local, and pop the values off of the stack one at a time:
void MathStack::addAll()
{
int num = 0, sum = 0;
while(!isEmpty())
{
pop(num);
sum += num;
}
push(sum);
}
Upvotes: 2
Reputation: 98509
The issue is that you want to break your loop when the stack has one item on it.
Imagine you start with a three-item stack:
4
8
2
You run your loop, pop 4 and 8, push 12. Now you have:
12
2
You run your loop again, pop 12 and 2, push 14. Now you have:
14
The stack isn't empty, so you go to pop twice...
You want to call isEmpty()
right after the first pop
(in addition to the call you have in the loop condition). If it tells you the stack is empty, the total sum of the whole stack is the value in num
.
Upvotes: 0