利用数组实现栈操作(go版本)

2022-04-09  本文已影响0人  小王同学123321
package main

import "fmt"

type Stacker interface {
    Newstack() interface{}
    IsEmpty() bool
    Pushstack(value interface{})
    Pop() interface{}
    Print()
    Clear()
}

type StackInfo struct {
    DataStore []interface{}
    Size int
}

func Newstack() *StackInfo{
    tmpstack := new(StackInfo)
    tmpstack.DataStore = make([]interface{},0)
    tmpstack.Size = 0
    return tmpstack
}

func (s *StackInfo) IsEmpty() bool{
    return s.Size == 0
}

func (s *StackInfo) Pushstack(value interface{}){
    s.DataStore = append(s.DataStore,value)
    s.Size++
}

func (s *StackInfo) Popstack() interface{}{
    length := len(s.DataStore)
    if length == 0{
        return nil
    } else if length == 1{
        return s.DataStore[0]
        s.Size--
    }else {
        popvalue := s.DataStore[length-1]
        s.DataStore = s.DataStore[:length-1]
        s.Size--
        return popvalue
    }
    return nil
}

func (s *StackInfo) Clear() *StackInfo {
    return new(StackInfo)
}

func (s *StackInfo) Print(){
    for index,v := range s.DataStore{
        fmt.Printf("%v---%v\n",index,v)
    }
}


func main(){
    stack := Newstack()
    stack.Pushstack("a")
    stack.Pushstack("1")
    stack.Pushstack("2")
    stack.Pushstack(1)
    fmt.Println(stack.Popstack())
    fmt.Println(*stack)
    stack.Print()
    fmt.Println(stack.Clear())
}
结果
上一篇下一篇

猜你喜欢

热点阅读