线性表中的一种特殊数据结构,数据只能从固定的一端插入数据或删除数据,另一端是封死的。 特点: FILO(First In Last Out): 先进后出; 栈满还存会“上溢”,栈空再取会“下溢”; “上溢”:在栈已经存满数据元素的情况下,如果继续向栈内存入数据,栈存储就会出错。 “下溢”:在栈内为空的状态下,如果对栈继续进行取数据的操作,
代码实现
package main
import (
"fmt"
"errors"
)
type Stack struct {
Max int
Top int
Arr [5]int
}
//入栈
func (this *Stack) Push(value int) (err error) {
if this.Top == this.Max - 1 {
return errors.New("栈满了")
}
this.Top++
this.Arr[this.Top] = value
return
}
//出栈
func (this *Stack) Pop() (value int,err error) {
if this.Top == -1 {
return 0,errors.New("栈为空")
}
value = this.Arr[this.Top]
this.Top--
return value,nil
}
//显示栈
func (this *Stack) Show() (err error) {
if this.Top == -1 {
return errors.New("栈为空")
}
for i := this.Top;i >= 0 ;i-- {
fmt.Println(this.Arr[i])
}
return
}
func main() {
stack := &Stack{
Max:5,
Top:-1,
}
stack.Push(1)
stack.Push(2)
stack.Push(3)
stack.Push(4)
stack.Push(5)
stack.Pop()
stack.Show()
}
结果
4
3
2
1
参考文档: