Junior — Middle
Explain how the stack data structure works and what operations it supports.
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 added element is the first to be removed. Imagine a stack of plates: to take a plate, you remove the top one.
Main operations of a stack:
- push — add an element to the top of the stack;
- pop — remove and return the top element;
- peek (or top) — view the top element without removing it;
- isEmpty — check if the stack is empty.
Example in JavaScript (Node.js):
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.isEmpty()) {
return null;
}
return this.items.pop();
}
peek() {
if (this.isEmpty()) {
return null;
}
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
}
const stack = new Stack();
stack.push(1);
stack.push(2);
console.log(stack.pop()); // 2
console.log(stack.peek()); // 1
This demonstrates the basic stack operations.