package main
import (
"fmt"
"errors"
)
type Stack struct {
Size int
Top int
arr [5]int
}
const INT_MAX = int(^uint(0) >> 1)
func (self *Stack) Push(ele int) (err error) {
if self.Top == self.Size - 1 {
err = errors.New("Stack full error!!")
return
}
self.Top++
self.arr[self.Top] = ele
return
}
func (self *Stack) Pop() (val int, err error) {
val = -INT_MAX
if self.Top == -1 {
err = errors.New("Stack empty error!!")
return
}
val = self.arr[self.Top]
self.Top--
return
}
func (self *Stack) List() {
if self.Top == -1 {
fmt.Println("Stack empty!!")
return
}
curPos := self.Top
for ;curPos!=-1; {
fmt.Println(self.arr[curPos])
curPos--
}
}
func main() {
stack := &Stack{
Size: 5,
Top: -1,
}
stack.Push(1)
stack.Push(2)
stack.Push(3)
stack.Push(4)
stack.Push(5)
fmt.Println("Current stack")
stack.List()
fmt.Println()
val, err := stack.Pop()
val, err = stack.Pop()
val, err = stack.Pop()
val, err = stack.Pop()
if err!=nil {
panic(err)
}
fmt.Printf("Current Pop: %d\n", val)
}
程序输出如下,
有疑问加站长微信联系(非本文作者)