当前位置:首页 > 编程语言 > 正文

数组模拟栈

11-19 编程语言

标签:使用数组   表示   tmp   使用   for   als   list   str   ==   

数组模拟栈(Stack)

package main

import (
    "fmt"
)

//使用数组模拟stack
type Stack struct {
    Max int //表示最大储存个数
    Maxtop int
    arr [5]int

}
func (s *Stack) IsStackFulll()(bool){
    if s.Maxtop == s.Max - 1 {
        return  true
    }
    return false

}

func (s *Stack) IsStackEmpty()(bool){
    if s.Maxtop == -1 {
        return  true
    }
    return false

}

func (s *Stack) Push(val int )(err error){
    if s.IsStackFulll(){
        fmt.Println("stack full")
        return fmt.Errorf("IsStackFulll")
    }
    //fmt.Println("s.Maxtop",s.Maxtop)
    s.Maxtop  
    s.arr[s.Maxtop] = val

    return
}

func (s *Stack) List()(err error){
    if s.IsStackEmpty() {
        fmt.Println("stack empty")
        return fmt.Errorf("stack empty")
    }
    tmp := s.Maxtop
    for {
        if tmp == -1 {
            break
        }

        fmt.Println(s.arr[tmp])
        tmp--

    }

    return
}

func (s *Stack) Pop()(val int,err error){
    if s.IsStackEmpty() {
        fmt.Println("stack empty")
        return 0,fmt.Errorf("stack empty")
    }
    val = s.arr[s.Maxtop]
    s.Maxtop--
    return
}




func main() {
    stack :=&Stack{
        Max:5,
        Maxtop:-1,
    }
    stack.Push(1)
    stack.Push(2)
    stack.Push(3)
    stack.Push(4)
    stack.Push(5)
    stack.Push(5)

    stack.List()
    fmt.Println("pop")
    fmt.Println(stack.Pop())
    fmt.Println(stack.Pop())
    fmt.Println(stack.Pop())
    fmt.Println(stack.Pop())

}

数组模拟栈

标签:使用数组   表示   tmp   使用   for   als   list   str   ==   

温馨提示: 本文由杰米博客推荐,转载请保留链接: https://www.jmwww.net/file/biancheng/12181.html