实现说明
整个示例围绕函数 push、pop、main组织。
这个示例中仅有的重复出现在 for len(q.stackIn) > 0 里。失败在这里是值:1 处检查 err 并当场决定,而不是让它向上冒。
使用要点
error在返回元组里,失败意味着什么由每个调用方决定。- 跑完文件,输出里会留下标记——
pop:、empty:。 - 运行整个文件:
main会依次驱动push、pop。
常见问题
调用失败时会发生什么?
Go 的惯用法:err 随调用返回,这里有 1 个检查点先测它再继续。
运行「两个栈拼出一个队列」会打印什么?
整个文件跑完,输出行以 pop:、empty: 这类前缀开头。
入口签名:func (q *queue) push(v int)
核心语句
return 0, errors.New("queue is empty")
for _, v := range []int{1, 2, 3} {
q.push(v)
}
func (q *queue) push(v int) {
q.stackIn = append(q.stackIn, v)
}
代码示例
package main
import (
"errors"
"fmt"
)
// queue backed by two stacks: stackIn receives, stackOut reverses for pops
type queue struct {
stackIn []int
stackOut []int
}
func (q *queue) push(v int) {
q.stackIn = append(q.stackIn, v)
}
func (q *queue) pop() (int, error) {
if len(q.stackOut) == 0 {
if len(q.stackIn) == 0 {
return 0, errors.New("queue is empty")
}
// 把入栈整批倒扣进出栈,保证先进先出
for len(q.stackIn) > 0 {
n := len(q.stackIn) - 1
q.stackOut = append(q.stackOut, q.stackIn[n])
q.stackIn = q.stackIn[:n]
}
}
n := len(q.stackOut) - 1
v := q.stackOut[n]
q.stackOut = q.stackOut[:n]
return v, nil
}
func main() {
var q queue
for _, v := range []int{1, 2, 3} {
q.push(v)
}
v, _ := q.pop()
fmt.Println("pop:", v)
q.push(4)
for i := 0; i < 3; i++ {
v, _ := q.pop()
fmt.Println("pop:", v)
}
if _, err := q.pop(); err != nil {
fmt.Println("empty:", err)
}
}