2022-11-29 01:09:12 +08:00
|
|
|
|
// File: array_stack.go
|
|
|
|
|
// Created Time: 2022-11-26
|
|
|
|
|
// Author: Reanon (793584285@qq.com)
|
|
|
|
|
|
|
|
|
|
package chapter_stack_and_queue
|
|
|
|
|
|
2022-12-03 20:25:24 +08:00
|
|
|
|
/* 基于数组实现的栈 */
|
2023-01-03 14:39:31 +08:00
|
|
|
|
type arrayStack struct {
|
2022-11-29 01:09:12 +08:00
|
|
|
|
data []int // 数据
|
|
|
|
|
}
|
|
|
|
|
|
2023-01-03 14:39:31 +08:00
|
|
|
|
func newArrayStack() *arrayStack {
|
|
|
|
|
return &arrayStack{
|
2022-11-29 01:09:12 +08:00
|
|
|
|
// 设置栈的长度为 0,容量为 16
|
|
|
|
|
data: make([]int, 0, 16),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-01-03 14:39:31 +08:00
|
|
|
|
// size 栈的长度
|
|
|
|
|
func (s *arrayStack) size() int {
|
2022-11-29 01:09:12 +08:00
|
|
|
|
return len(s.data)
|
|
|
|
|
}
|
|
|
|
|
|
2023-01-03 14:39:31 +08:00
|
|
|
|
// isEmpty 栈是否为空
|
|
|
|
|
func (s *arrayStack) isEmpty() bool {
|
|
|
|
|
return s.size() == 0
|
2022-11-29 01:09:12 +08:00
|
|
|
|
}
|
|
|
|
|
|
2023-01-03 14:39:31 +08:00
|
|
|
|
// push 入栈
|
|
|
|
|
func (s *arrayStack) push(v int) {
|
2022-11-29 01:09:12 +08:00
|
|
|
|
// 切片会自动扩容
|
|
|
|
|
s.data = append(s.data, v)
|
|
|
|
|
}
|
|
|
|
|
|
2023-01-03 14:39:31 +08:00
|
|
|
|
// pop 出栈
|
|
|
|
|
func (s *arrayStack) pop() any {
|
2022-11-29 01:09:12 +08:00
|
|
|
|
// 弹出栈前,先判断是否为空
|
2023-01-03 14:39:31 +08:00
|
|
|
|
if s.isEmpty() {
|
2022-11-29 01:09:12 +08:00
|
|
|
|
return nil
|
|
|
|
|
}
|
2023-01-03 14:39:31 +08:00
|
|
|
|
val := s.peek()
|
2022-11-29 01:09:12 +08:00
|
|
|
|
s.data = s.data[:len(s.data)-1]
|
|
|
|
|
return val
|
|
|
|
|
}
|
|
|
|
|
|
2023-01-03 14:39:31 +08:00
|
|
|
|
// peek 获取栈顶元素
|
|
|
|
|
func (s *arrayStack) peek() any {
|
|
|
|
|
if s.isEmpty() {
|
2022-11-29 01:09:12 +08:00
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
val := s.data[len(s.data)-1]
|
|
|
|
|
return val
|
|
|
|
|
}
|
|
|
|
|
|
2022-12-03 20:25:24 +08:00
|
|
|
|
// 获取 Slice 用于打印
|
2023-01-03 14:39:31 +08:00
|
|
|
|
func (s *arrayStack) toSlice() []int {
|
2022-12-03 20:25:24 +08:00
|
|
|
|
return s.data
|
2022-11-29 01:09:12 +08:00
|
|
|
|
}
|