#C14016. Stack Implementation Challenge

    ID: 43619 Type: Default 1000ms 256MiB

Stack Implementation Challenge

Stack Implementation Challenge

You are required to implement a stack data structure that supports the following operations:

  • push x: Push the integer x onto the stack.
  • pop: Remove the top element of the stack and print it. If the stack is empty, print error.
  • top: Print the top element of the stack without removing it. If the stack is empty, print error.
  • isEmpty: Print true if the stack is empty; otherwise, print false.

The operations are given as commands from stdin. Your stack should behave according to the Last-In-First-Out (LIFO) principle. Specifically, if we denote the stack as \( S = \{a_1, a_2, \ldots, a_n\} \) where \( a_n \) is the top element, then:

\[ \begin{aligned} \text{push}(x):&\quad S \leftarrow S \cup \{x\} \\ \text{pop}():&\quad \text{if } S \neq \emptyset,\\ \ &\quad \text{remove } a_n \text{ and return it, otherwise output error} \\ \text{top}():&\quad \text{if } S \neq \emptyset,\\ \ &\quad return }a_n\text{ without removal, otherwise output error} \\ \text{isEmpty}():&\quad \text{return } \begin{cases} \text{true} & \text{if } S = \emptyset \\ \text{false} & \text{otherwise} \end{cases} \end{aligned} \]

Implement the stack and process a series of commands accordingly.

inputFormat

The first line of input contains an integer n (1 ≤ n ≤ 105), representing the number of operations.

Each of the following n lines contains one of the following commands:

  • push x where x is an integer (\(-10^9 \le x \le 10^9\)).
  • pop
  • top
  • isEmpty

Note: For push commands, no output is expected.

outputFormat

For each command that produces an output (pop, top, isEmpty), print the result on a separate line. The outputs are defined as follows:

  • For pop and top: print the integer value if the stack is non-empty. If the stack is empty, print error.
  • For isEmpty: print true if the stack is empty, otherwise print false.
## sample
5
push 10
push 20
top
pop
top
20

20 10

</p>