go語言-golang基礎-queue隊列和stack堆棧


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

*/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM