Stack
A stack is a LIFO structure: the last value pushed is the first value popped.
ابدأ بهذا النموذج الذهني
A stack is a LIFO structure: the last value pushed is the first value popped.
كيف يعمل، بلا مصطلحات زائدة
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).
اقرأ الخوارزمية كسلسلة من القرارات
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; }
}لا تحفظ الصياغة. تتبع الحالة التي تتغير في كل سطر واربطها بالثابت الموضح أعلاه.
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.
مناسب لـ
- Undo/redo
- Expression parsing
- DFS and backtracking
ما الذي يسوء عادةً
- Popping from an empty stack without handling it.
- Using Array.shift() and accidentally making operations O(n).
صيغة إجابة احترافية
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.
ماذا يجب أن أذكر عن التعقيد؟
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.
ما الخطأ الأكثر شيوعاً؟
Popping from an empty stack without handling it.