Junior — Middle
Can you explain the principle of a stack data structure?
sobes.tech AI
Answer from AI
A stack is a data structure that operates on the Last In, First Out (LIFO) principle, meaning the last element added is the first to be removed.
Main operations of a stack:
- push — adding an element to the top of the stack;
- pop — removing and returning the top element;
- peek (or top) — viewing the top element without removing it.
Example: if elements 1, 2, 3 are added sequentially to the stack, then when removing, 3 will come out first, then 2, then 1.
Stacks are widely used for implementing function calls, undo actions, expression parsing, etc.