- stack1.push(10)
-
stack1.push(8)
-
stack2.push(2)
-
stack1.push(3)
-
-
while !(stack1.isempty())
-
x=stack1.top;
-
stack1.pop();
-
stack1.pop();
-
stack2.push(x);
First of all, this little section of code is an error and will result in an infinite loop. There are no curly brackets around the loop, so only the first statement is executed - x is continually assigned stack1.top, andsince the stack never changes, the loop condition never changes. However, I understand that this is likely a typo, and so I'm assuming you meant to write
- while (!(stack1.isEmpty())) {
-
x = stack1.top; // should be stack1.top()?
-
stack1.pop();
-
stack1.pop();
-
stack2.push(x);
-
}
My interpretation is I first push all elements into either stack 1 or 2.
So stack 1 would be:
3
8
10
Stack 2 would be
2
That is correct.
Then after the first loop
since Stack1 is not empty x =3
stack1.pop(); will pop 3
stack1.pop(); will pop 8
leaving 10 as x?? and then I push that over to stack 2 leaving stack 1 empty??
Here, you make two mistakes. In one execution of the loop, x is assigned only once, at the beginning, to stack1.top. That is currently 3. So x is an integer variable holding the value 3. Then you pop two values - 3 and 8 - leaving stack1 to hold 10 and stack2 to hold 2. x still holds 3! It has not been assigned anything else! You then push x (3) onto stack2. So after 1 execution, stack1 holds 10, and stack2 holds 3, 2.
Can you see what will happen in the second execution of the loop?