golang顺序栈实现

package main

import (
   "fmt"
)

type arraystack struct {
   items []string//切片
   count int  //栈中元素个数
   n int  //栈的大小
}

//初始化
func (this *arraystack) arraystack(n int){
   this.n=n
   this.count=0
}

//入栈
func (this *arraystack) push(item string){
   if this.count==this.n {
      fmt.Println("栈空间已满")
      return
   }
   this.items=append(this.items,item)
   this.count++

}

//出栈
func(this *arraystack) pop(){
   if 0==this.count{
      fmt.Println("栈已空")
      return
   }
   this.items=this.items[0:len(this.items)-1]
   this.count--

}

//打印输出
func (this arraystack)printstack(){
   for i:=len(this.items)-1;i>=0;i--{
      fmt.Printf("%s-",this.items[i])
   }
}
func main(){
   stack:=new(arraystack)
   stack.arraystack(5)
   stack.push("1")
   stack.push("2")
   stack.push("3")
   stack.push("4")
   stack.push("5")
   stack.printstack()
   fmt.Println()
   stack.pop()
   stack.printstack()

}

版权声明:本文为qq_41450275原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。