(转)go语言-golang基础-queue队列和stack堆栈

原文:https://www.cnblogs.com/malukang/p/12708850.html

1. queue队列

队列(queue), 是一种FIFO(First In First Out)先进先出的线性表。通常用数据或者链表来实现队列。 队列只允许在后端插入,前端删除操作。
性质:
先进先出

复制代码
复制代码
package main

import "fmt"

func main() {
    //队列
    //先进先出
    queue := []string{}
    //push
    //append
    queue = append(queue, "a", "b")
    queue = append(queue, "c")
    //pop
    x := queue[0]
    queue = queue[1:]
    fmt.Println("1: ", x)

    x = queue[0]
    queue = queue[1:]
    fmt.Println("2: ", x)

    x = queue[0]
    queue = queue[1:]
    fmt.Println("3: ", x)

}

/*
$ go run queue.go
1:  a
2:  b
3:  c
*/
复制代码
复制代码

 

2. stack堆栈

先进后出

示例:

复制代码
复制代码
package main

import "fmt"

func main() {
    //堆栈
    //先进后出
    stack := []string{}
    //push
    //append
    stack = append(stack, "a")
    stack = append(stack, "b")
    stack = append(stack, "c")
    //pop
    //后面移除
    x := stack[len(stack)-1]
    stack = stack[:len(stack)-1]
    fmt.Println("1: ", x)

    x = stack[len(stack)-1]
    stack = stack[:len(stack)-1]
    fmt.Println("2: ", x)

    x = stack[len(stack)-1]
    stack = stack[:len(stack)-1]
    fmt.Println("3: ", x)
}
/*
$ go run stack.go
1:  c
2:  b
3:  a

*/
复制代码
复制代码
posted @   liujiacai  阅读(497)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示