Junior
What are the main functions of a stack?
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 functions of a stack:
- push(element) — adds an element to the top of the stack.
- pop() — removes and returns the element from the top of the stack.
- peek() or top() — returns the element at the top of the stack without removing it.
- isEmpty() — checks if the stack is empty.
Example in Kotlin:
val stack = mutableListOf<Int>()
// Add an element
stack.add(10) // push
// Get the top element
val top = stack.last() // peek
// Remove the top element
val removed = stack.removeAt(stack.size - 1) // pop
// Check if empty
val empty = stack.isEmpty()