Stack
A stack is a LIFO structure: the last value pushed is the first value popped.
Beginne mit diesem mentalen Modell
A stack is a LIFO structure: the last value pushed is the first value popped.
So funktioniert es – ohne unnötigen Jargon
Think of a stack of plates. You add and remove from one end only.
Core operations are push, pop and peek/top. With a good implementation they are O(1).
Lies den Algorithmus als Folge von Entscheidungen
Push adds to the top.
Pop removes and returns the top.
Peek reads the top without removing it.
push(1), push(2), pop() returns 2.
class Stack {
#items = [];
push(value) { this.#items.push(value); }
pop() { return this.#items.pop(); }
peek() { return this.#items.at(-1); }
get size() { return this.#items.length; }
}Lerne die Syntax nicht auswendig. Folge dem Zustand, der sich in jeder Zeile ändert, und verbinde ihn mit der oben beschriebenen Invariante.
push/pop O(1)
Do not quote this complexity mechanically. Ask which operation or input dimension it describes, then derive the cost from the loops, recursion depth, data-structure operations and any preprocessing assumptions.
Gut geeignet
- Undo/redo
- Expression parsing
- DFS and backtracking
Was typischerweise schiefgeht
- Popping from an empty stack without handling it.
- Using Array.shift() and accidentally making operations O(n).
Struktur einer professionellen Antwort
Say LIFO first, then name push/pop/peek and one real use such as call stacks or parsing.
What problem does Stack solve?
A stack is a LIFO structure: the last value pushed is the first value popped.
Was sollte ich zur Komplexität erwähnen?
Its typical cost here is push/pop O(1), but a complete answer should connect that cost to the representation, input constraints and the dominant operations.
Was ist der häufigste Fehler?
Popping from an empty stack without handling it.