ENع
→Stacks at work
الدرس 07 · Linear structures in depth

Stacks at work: brackets, undo and expression evaluation

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

12 دقيقة10 خطوات5 أسئلةBeginner
عن هذا الدرس

A stack only lets you touch its top item, and that turns out to be exactly what many real problems need. Feed one stack three different inputs and watch every token hop on or off: a bracket checker that pushes each opener and lets each closer pop its partner, an editor's undo stack, and a calculator that evaluates postfix expressions like 3 4 + 2 *. The Software lesson "Stacks and queues" introduces push and pop with a Python list, and "Linked lists: singly, doubly and circular" shows another way to build one.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 7 · تفاعلي
01 / 10

Brackets close in reverse

In ([]{}) every closing bracket must match the most recent bracket still open. Most recent first is last in, first out: the rule of a stack. A Python list works as one: append() pushes on top, pop() takes the top off.

input: "([]{})"
rule: a closer must match the newest opener still open
stack = []          # a Python list
stack.append(x)     # push x on top
stack.pop()         # remove and return the top
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Brackets close in reverse

    In ([]{}) every closing bracket must match the most recent bracket still open. Most recent first is last in, first out: the rule of a stack. A Python list works as one: append() pushes on top, pop() takes the top off.

    input: "([]{})"
    rule: a closer must match the newest opener still open
    stack = []          # a Python list
    stack.append(x)     # push x on top
    stack.pop()         # remove and return the top
  2. Openers go on the stack

    Read the input left to right. ( is an opener, so line 6 pushes it. [ is an opener too, so it lands on top of (. The stack holds exactly the brackets still waiting for a partner.

    balanced("([]{})")
    stack before: []
      (    push (  → ['(']
      [    push [  → ['(', '[']
  3. A closer pops its partner

    ] is a closer. Line 8 pops the top item and checks that it is the matching opener. The top is [, so the pair is good and both are done. ( still waits underneath.

    balanced("([]{})")
    stack before: ['(', '[']
      ]    pop [: a match  → ['(']
  4. Only the top is checked

    { is pushed on top of (. Then } pops it: a match. A closer only ever looks at the top of the stack, never deeper, so each character costs one push or one pop.

    balanced("([]{})")
    stack before: ['(']
      {    push {  → ['(', '{']
      }    pop {: a match  → ['(']
  5. Empty at the end: balanced

    ) pops (, the last opener. The loop ends and line 10 returns not stack: an empty stack means every opener found its partner, so the answer is True. The work grows in step with the length: O(n).

    balanced("([]{})")
    stack before: ['(']
      )    pop (: a match  → []
    loop ends: stack == []
    return not stack  → True
  6. Two ways to fail

    In (] the closer ] pops (, the wrong partner, so line 9 returns False. A string like (( fails the other way: the loop ends with ( still on the stack, so not stack is False.

    balanced("(]")
    stack before: []
      (    push (  → ['(']
      ]    pop (: wrong partner → return False
    balanced("((") → False: the loop ends with
      ['(', '('] still on the stack
  7. Undo: every edit is pushed

    A text editor uses the same idea. Each time you type, it pushes a note of that edit onto an undo stack. Type c, a, t and the stack holds +c, +a, +t, newest on top.

    typing c, a, t, then undo
    stack before: []
      c    push +c  → ['+c']
      a    push +a  → ['+c', '+a']
      t    push +t  → ['+c', '+a', '+t']
    text = "cat"
  8. Undo pops the newest edit

    Press undo and the editor pops the top edit, +t, and reverses it: the text goes from cat back to ca. Press it again and +a comes off next. Undo always takes back the newest change first.

    typing c, a, t, then undo
    stack before: ['+c', '+a', '+t']
      undo pop +t  → ['+c', '+a']
    text = "cat"[:-1] = "ca"
  9. Postfix: numbers wait

    In postfix the operator comes after its two numbers: 3 4 + 2 * means (3 + 4) × 2. Numbers are pushed. + pops 4, then 3, adds them and pushes 7.

    eval_postfix("3 4 + 2 *".split())
    stack before: []
      3    push 3  → [3]
      4    push 4  → [3, 4]
      +    pop 4 and 3, push 7  → [7]
  10. The last item is the answer

    2 is pushed on top of 7. * pops 2, then 7, multiplies and pushes 14. At the end one number is left on the stack: the answer, 14. No brackets or precedence rules were needed.

    eval_postfix("3 4 + 2 *".split())
    stack before: [7]
      2    push 2  → [7, 2]
      *    pop 2 and 7, push 14  → [14]
    return stack.pop()  → 14
    (3 + 4) * 2 == 14

اختبار يتاح بعد الخطوة الأخيرة.