实现说明
底层就是函数 Push、Pop、Peek、main。
循环只出现在 for,它的每次迭代处理一个元素。
使用要点
- 演示输出是带标签的(
peek:、stack drained、undo:),每个操作都会留下自己的一行标注。 - 运行整个文件:
main会依次驱动Push、Peek、Pop。
常见问题
运行「用 slice 实现栈的 push/pop/peek」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 peek:、stack drained、undo: 这类标签。
主要签名是 func (s *Stack) Push(item string)
核心语句
func (s *Stack) Peek() (string, bool) {
if len(*s) == 0 {
return "", false
}
return (*s)[len(*s)-1], true
}
func (s *Stack) Pop() (string, bool) {
if len(*s) == 0 {
return "", false // empty stack: report via the ok flag instead of panicking
}
n := len(*s) - 1
item := (*s)[n]
*s = (*s)[:n] // truncate so the backing array stops holding the popped value
return item, true
}
func (s *Stack) Push(item string) {
*s = append(*s, item)
}
代码示例
package main
import "fmt"
// a stack built on a slice: push uses append, while pop and peek check for an empty stack first
type Stack []string
func (s *Stack) Push(item string) {
*s = append(*s, item)
}
func (s *Stack) Pop() (string, bool) {
if len(*s) == 0 {
return "", false // empty stack: report via the ok flag instead of panicking
}
n := len(*s) - 1
item := (*s)[n]
*s = (*s)[:n] // truncate so the backing array stops holding the popped value
return item, true
}
func (s *Stack) Peek() (string, bool) {
if len(*s) == 0 {
return "", false
}
return (*s)[len(*s)-1], true
}
func main() {
var undo Stack
undo.Push("rename column")
undo.Push("drop index")
if top, ok := undo.Peek(); ok {
fmt.Println("peek:", top)
}
for {
item, ok := undo.Pop()
if !ok {
fmt.Println("stack drained")
break
}
fmt.Println("undo:", item)
}
}