Stack — Push and Pop
Practice this coding question on Coding Gurukul.
Problem statement
Implement a stack that starts empty. - PUSH x: add x to the top. - POP: remove and print the top value. - TOP: print the top value without removing it. - SIZE: print the number of values. If POP or TOP is called on an empty stack, print EMPTY. PUSH produces no output. The last value pushed is the first value popped. Support each command in O(1) amortized time. Worked example PUSH 4 and PUSH 8 put 8 on top. TOP prints 8, and POP removes and prints 8. SIZE prints 1. The next POP prints 4, then another POP prints EMPTY. The final SIZE is 0.
Input format
First line: q. Next q lines: PUSH x, POP, TOP, or SIZE.
Output format
One line for every POP, TOP or SIZE.
Constraints
1 <= q <= 100000; -10^9 <= x <= 10^9. At least one output command.
Sample input
8 PUSH 4 PUSH 8 TOP POP SIZE POP POP SIZE
Sample output
8 8 1 4 EMPTY 0
Sign in to run or submit a solution in C++, Java or Python.