Lesson 77: Stack
หน้านี้ต้องใช้เบราว์เซอร์ล่าสุด (รองรับ SharedArrayBuffer) กรุณาอัปเดต Chrome, Edge, Firefox หรือ Safari เป็นเวอร์ชันล่าสุด
English
Last in, first out
- A stack is like a pile of plates: you add (push) and remove (pop) only at the top.
- The stack pointer
spshows the next free place. Push stores atspand adds 1; pop subtracts 1 and takes that item. - Check before you push (full?) and before you pop (empty?).
| After | Places 1 2 3 4 | sp |
|---|---|---|
| start | – – – – | 1 |
| push 3 | 3 – – – | 2 |
| push 8 | 3 8 – – | 3 |
| pop → 8 | 3 – – – | 2 |

- Robots lesson 47 has the opposite: a queue, first in, first out.
English
In the exam
- 9618/22/O/N/24 Q3: a stack in ThisStack[1:60] with SP pointing to the next available place and OnStack counting the items. (a)(i) Initial values. Mark scheme: SP = 1, OnStack = 0. (a)(ii) Why the array needs no initial values: an unused place is never popped before a value has been pushed into it. (b) Complete Push. Mark scheme: IF the stack is full (OnStack = 60 or SP = 61) THEN RETURN FALSE; ThisStack[SP] ← ThisValue; SP ← SP + 1.
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
A stack has room for 4 numbers, in places 1 to 4. sp is the stack pointer: the next free place, so it starts at 1. Finish push: if the stack is full, return false; else store the value at place sp, add 1 to sp and return true. Type numbers in the Serial Monitor.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Now type P ไป pop: take the top item off the stack. Finish pop (the top item is one place below sp), and print Stack empty when there is nothing to pop.
คลิก Run เพื่อดูผลลัพธ์ที่นี่