Eranka
Eranka

Reputation: 11

Data Structure : Stack

1.theStack.push(1);
2.theStack.push(2);
3.theStack.push(3);
4.theStack.push(theStack.pop()); 
5.theStack.push(theStack.pop() +theStack.pop()); 
6.theStack.push(6); 
7.theStack.push(7); 
8.theStack.push(theStack.pop() * theStack.pop());

When first 3 lines are executed output will be

|3|
|2|
|1|

I have a problem understanding above mentioned lines. Could anyone please explain above line. What happens with 4th-8th lines?

Upvotes: 1

Views: 83

Answers (1)

Mureinik
Mureinik

Reputation: 310983

Assuming pop0 is a typo and it's supposed to be a call to pop(), it removes the last element you pushed to the stack and returns it. Let's follow the program:

theStack.push(1);
// 1 is pushed to the stack. The stack now contains [1]

theStack.push(2);
// 2 is pushed to the stack. The stack now contains [2, 1]

theStack.push(3);
// 3 is pushed to the stack. The stack now contains [3, 2, 1]

theStack.push(theStack.pop()); 
// 3 is popped, and then pushed back in, so the stack still contains [3, 2, 1]

theStack.push(theStack.pop() + theStack.pop()); 
// 3 and 2 are popped, added, and pushed back in, so the stack now contains 
// [5, 1]

theStack.push(6); 
// 6 is pushed to the stack. The stack now contains [6, 5, 1]

theStack.push(7); 
// 7 is pushed to the stack. The stack now contains [7, 6, 5, 1]

theStack.push(theStack.pop() * theStack.pop());
// 7 and 6 are popped, multiplied, and pushed back in, so the stack now contains
// [42, 5, 1]

Upvotes: 3

Related Questions