Junior
How does a stack work in the context of programming?
sobes.tech AI
Answer from AI
A stack is an abstract data type that operates on the Last-In, First-Out (LIFO) principle.
Main operations:
- Push: Add an element to the top of the stack.
- Pop: Remove and return the top element.
- Peek (or Top): Return the top element without removing it.
- isEmpty: Check if the stack is empty.
- size: Return the number of elements in the stack.
Example implementation of a stack in Kotlin using MutableList:
class Stack<T> {
private val elements = mutableListOf<T>()
fun push(item: T) {
elements.add(item)
}
fun pop(): T? {
return if (!isEmpty()) {
elements.removeAt(elements.size - 1)
} else {
null // Or throw exception
}
}
fun peek(): T? {
return if (!isEmpty()) {
elements.last()
} else {
null
}
}
fun isEmpty(): Boolean {
return elements.isEmpty()
}
fun size(): Int {
return elements.size
}
}
Common uses of stack in programming include:
- Expression evaluation: Converting infix to postfix/prefix notation, evaluating postfix expressions.
- Function/method call management: Call stack stores information about active functions.
- Undo/redo actions: Used in editors, graphic editors for history.
- Graph and tree traversal: Used for depth-first search (DFS).
- Syntax analysis: Parsers use stacks to check syntax correctness.
Stacks are fundamental data structures with important roles in many algorithms, operating system mechanisms, and virtual machines.