美文网首页
Go数据结构——栈

Go数据结构——栈

作者: ProgrammingGuy | 来源:发表于2020-02-09 15:33 被阅读0次
    package main
    
    import (
        "fmt"
    )
    
    type stack struct {
        filled int
        data   [10]int
    }
    
    func (s *stack) push(value int) {
        if s.filled == 10 {
            panic("stack is full")
        }
        s.data[s.filled] = value
        s.filled++
    }
    
    func (s *stack) empty() bool {
        return s.filled == 0
    }
    
    func (s *stack) pop() int {
        if s.empty() {
            panic("stack is empty")
        }
        s.filled--
        return s.data[s.filled]
    }
    
    func (s *stack) print() {
        for _, v := range s.data {
            fmt.Println(v)
        }
    }
    
    func main() {
        s := stack{}
        for i := 0; i < 10; i++ {
            s.push(i)
        }
        s.print()
    
        fmt.Println("---------------------")
    
        for i := 0; i < 5; i++ {
            fmt.Println(s.pop())
        }
    
        fmt.Println("---------------------")
    
        for i := 0; i < 5; i++ {
            fmt.Println(s.pop())
        }
    
        fmt.Println("---------------------")
    
        for i := 0; i < 1; i++ {
            fmt.Println(s.empty())
        }
    }
    

    相关文章

      网友评论

          本文标题:Go数据结构——栈

          本文链接:https://www.haomeiwen.com/subject/irxnxhtx.html