数据结构和算法-go 切片实现栈和队列

type Stack struct {
    list []interface{}
}
func NewStack() *Stack{
    return new(Stack)
}
func (s *Stack) Push(value interface{}) {
    s.list = append(s.list, value)
}
func (s *Stack) Pop () interface{}{
    len := len(s.list)
    var value interface{}
    if len==0 {
        return nil
    }else if len==1{
        value = s.list[0]
        s.list = []interface{}{}
    }else{
        value = s.list[len-1]
        s.list = s.list[len-2:len-1]
    }
    return value
}
func (s *Stack) Print() {
    for _,v := range s.list {
        fmt.Printf("%v",v)
    }
    fmt.Printf("\n")
}

func main(){
    stack := NewStack()
    stack.Push(1)
    stack.Push(2)
    res1:= stack.Pop()
    res2:= stack.Pop()
    res3:= stack.Pop()
    fmt.Println(res1,res2,res3)

}
func main() {
    q := NewQueue()
    q.Push(12)
    q.Push(15)
    q.Pop()
    q.Print()
}
type Queue struct {
    list []interface{}
}
func NewQueue() *Queue{
    list := make([]interface{},0)
    return &Queue{list:list}
}
func (q *Queue)Push(data interface{}) {
    q.list = append(q.list,data)
}

func (q *Queue)Pop() interface{}{
    if len(q.list)==0 {
        return nil
    }
    res := q.list[0]
    q.list = q.list[1:]
    return res
}
func (q *Queue)Print(){
    for _,val := range q.list {
        fmt.Println(val)
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
用过哪些工具?为啥用这个工具(速度快,支持高并发...)?底层如何实现的?
讨论数量: 1

为什么还要判断长度为1的情况

3年前 评论
Runtoweb3 (楼主) 3年前
caoayu (作者) 3年前
caoayu (作者) 3年前
Runtoweb3 (楼主) 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!