What is a stack as a data structure?
A stack is a data structure that works on the LIFO (Last In, First Out) principle: last in, first out.
Imagine a stack of plates: to take the bottom one, you need to remove everything on top of it.
A stack has two basic actions:
- push(x): place an element on top of the stack,
- pop(): remove the top element.
Additionally, these are often used:
- peek() / top(): view the top element without removing it,
- isEmpty(): check whether the stack is empty.
A stack is used in:
- handling function calls (call and return),
- undoing actions (undo in editors),
- checking brackets,
- implementing recursion and parsing expressions.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.