#K58422. Implement a Basic Stack
Implement a Basic Stack
Implement a Basic Stack
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 from the stack and print it. If the stack is empty, print
Stack is empty
. - peek: Print the top element of the stack without removing it. If the stack is empty, print
Stack is empty
. - is_empty: Print
True
if the stack is empty, otherwise printFalse
. - size: Print the number of elements in the stack.
The input will consist of a series of commands. You should implement these operations accordingly.
Note: For any operation that returns a value, print each result in a new line in the order the operations appear.
The underlying idea is to simulate a stack as defined mathematically by its last-in-first-out (LIFO) property. In mathematical notation, a stack can be represented as a sequence \(S = [s_1, s_2, \ldots, s_n]\), where pushing an element \(x\) appends it to the sequence, and popping removes the element \(s_n\). If \(S\) is empty, operations like pop
and peek
should return "Stack is empty".
inputFormat
The first line contains an integer n representing the number of commands. The following n lines each contain a command.
Each command is one of the following formats:
push x
(where x is an integer)pop
peek
is_empty
size
outputFormat
For every operation that produces a result (pop
, peek
, is_empty
, and size
), output the result on a separate line.
If an operation is executed on an empty stack for pop
or peek
, output "Stack is empty".
5
push 1
push 2
size
pop
peek
2
2
1
</p>