go语言实现基本的栈操作

package main

import (
 
  "fmt"
   "errors"
)

func testLineStack() {
   ls := initLineStack()
   fmt.Printf("isEmpty=%#", ls.isEmpty())
   fmt.Println()
   for i:=0; i<=6; i++ {
      ls.push(i)
   }
   fmt.Printf("Node=%#", ls.Node)
   fmt.Println()
   ls.pop()
   ls.pop()
   fmt.Printf("Node=%#", ls.Node)
   fmt.Println()
   t,_ := ls.getTop()
   fmt.Println(t)
   ls.destroy()
}

const SIZE = 10

type LineStack struct {
   Node [SIZE]int
   Top int
}

func initLineStack() *LineStack {
   node := [SIZE]int{0,0,0,0,0,0,0,0,0,0}
   return &LineStack{node, 0}
}

func (ls *LineStack)isEmpty() bool {
   if ls.Top == 0 {
      return true
   }
   return false
}

func (ls *LineStack)push(ele int) (bool, error) {
   if ls.Top == len(ls.Node) {
      return false, errors.New("已满")
   }
   ls.Node[ls.Top] = ele
   ls.Top++
   return true, nil
}

func (ls *LineStack)pop() (int, error) {
   if ls.Top == 0 {
      return 0, errors.New("空")
   }
   ls.Top--
   ls.Node[ls.Top] = 0
   return ls.Node[ls.Top], nil
}

func (ls *LineStack)getTop() (int, error) {
   if ls.Top == 0 {
      return 0, errors.New("空")
   }
   return ls.Node[ls.Top-1], nil
}

func (ls *LineStack)destroy() error {
   if ls.Top == 0 {
      return errors.New("空")
   }
   ls = nil
   return nil
}

你可能感兴趣的:(go语言显现栈操作)