Junior — Middle
What is the data structure Stack and what data is usually stored in it?
sobes.tech AI
Answer from AI
The Stack data structure is a collection of elements with the LIFO (Last In, First Out) principle, meaning the last added element is the first to be retrieved.
Typically, a stack stores data that needs to be processed in reverse order, such as:
- Function calls (call stack)
- Operands and operators during expression evaluation
- Temporary data during graph or tree traversal
Example of using a stack in Java:
Stack<Integer> stack = new Stack<>();
stack.push(1); // add element
stack.push(2);
int top = stack.pop(); // retrieve the last added element (2)
Stacks are widely used for managing states, undo operations, parsing, etc.