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) Travel() {
if this.Empty(){
fmt.Println("棧爲空")
return
}
for i:=0;i<=this.top;i++{
fmt.Printf("%v ", this.data[i])
}
}
func (this *stack) Length() int {
return this.top + 1
}
func (this *stack) Clear() {
this.top = -1
}
func main() {
s := initStack()
...
}