package main
import (
//"errors"
"fmt"
)
type stack struct {
size int // 栈容量
top int // 栈顶
data []interface{} // 数据
}
const stackSize = 15
var stackData = make([]interface{}, stackSize)
// 初始化栈
func initStack() stack {
s := stack{
size: stackSize,
top: -1,
data: stackData,
}
return s
}
func (this *stack) Empty() bool {
// 判断栈是否为空
return this.top == -1
}
func (this *stack) IsFull() bool {
// 判断栈是否已满
return this.top == this.size - 1
}
func (this *stack) Push(val interface{}) bool {
// 入栈
if this.IsFull() {
fmt.Println("栈已满")
//return errors.New("Stack isFull")
return false
}
this.top += 1 // 栈顶加1
//fmt.Println(val.(string))
this.data[this.top] = val // 将当前元素放在栈顶
return true
}
func (this *stack) Pop() interface{}{
if this.Empty(){
fmt.Println("栈是空的")
return nil
}
popIndex := this.top
this.top--
return this.data[popIndex]
}
func (this *stack) Tr
Go数据结构之栈 stack
最新推荐文章于 2022-02-11 19:43:13 发布