此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
什么是 ADT?
- 抽象数据类型(ADT,Abstract Data Type)是一组数据加上对它的一组操作。
- 你使用这些操作,而不必关心它内部是怎么实现的。
- 栈(stack)、队列(queue)和链表(linked list)都是 ADT。
栈是 LIFO
- 栈是后进先出(LIFO,Last In, First Out)。
- 你最后放进去的元素,会最先被取出来。
- 想象一摞盘子:你先拿最上面的那一个。
用列表实现 push 和 pop
- 我们可以用一个 Python 列表来构建栈。
- push(入栈)=
stack.append(x)—— 加到末尾(栈顶)。 - pop(出栈)=
stack.pop()—— 移除并返回末尾(栈顶)。
English
stack = []
stack.append("a")
stack.append("b")
print(stack.pop())
print(stack)
peek 与判空
- peek(查看栈顶)而不移除它:
stack[-1]。 - 当
len(stack) == 0时,栈是空的。 - 对空栈做 pop 会出错,所以要先检查。
English
stack = [10, 20, 30]
print(stack[-1]) # peek the top
print(len(stack) == 0) # is it empty?
用剑桥伪代码表示
- 考试用一个数组加上一个
top指针(一个索引)来构建栈。
DECLARE stack : ARRAY[1:10] OF INTEGER
DECLARE top : INTEGER
top ← 0 // 0 means empty
// push value
top ← top + 1
stack[top] ← value
// pop into value
value ← stack[top]
top ← top - 1
常见错误
- 栈是后进先出:从顶部压入,从顶部弹出。
- pop 之前先检查它不是空的。
现在轮到你
- 把列表当作你的栈(用
append入栈,用pop移除)。 - 按检查答案来测试你的代码。
探索
A stack is LIFO
A stack pushes and pops at one end — last in, first out.
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
Start with an empty stack. Push 1, then 2, then 3. Then pop once, storing the removed value in top. (top should be 3 and the stack should be [1, 2].)
点击“运行”查看此处输出。
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
Use a stack to 逆向 the list items. Push every item onto a stack, then pop them all into result. (result should be [3, 2, 1].)
点击“运行”查看此处输出。
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
Write top(stack) that 返回值 the top item (the last one) without removing it. If the stack is empty, return None.
点击“运行”查看此处输出。