天天看點

golang用slice、list當queue

背景

golang沒有queue這種類型,不過可以用slice、list模拟

slice當queue

聲明隊列
var queue []int

入隊一個元素:
queue = append(queue, 1)

出隊一個元素:
if len(queue) > 1 {
    queue = queue[1:]
}      

問題:當不斷入隊列時,需不停的擴容

list當queue

初始化一個隊裡:
queue := list.New()

入隊一個元素:
queue.PushBack(1)

出隊一個元素:
if queue.Len() > 1 {
    queue.Remove(queue.Front())
}      

執行個體:層次周遊二叉樹

golang用slice、list當queue

list題解

func levelOrderBottom(root *TreeNode) [][]int {
    var result [][]int
    if root == nil {
        return result
    }
    queue := list.New()
    queue.PushBack(root)
    for queue.Len() > 0 {
        curlen := queue.Len()
        var curList []int
        for i:= 0; i < curlen; i++ {
            curTree := queue.Remove(queue.Front()).(*TreeNode)
            curList = append(curList, curTree.Val)
            if curTree.Left != nil {
                queue.PushBack(curTree.Left)
            }
            if curTree.Right != nil {
                queue.PushBack(curTree.Right)
            }
        }
        result = append([][]int{curList}, result...)
    }
    return result
}      

list用法

type Element
    func (e *Element) Next() *Element
    func (e *Element) Prev() *Element

type List
    func New() *List
    func (l *List) Back() *Element   // 最後一個元素
    func (l *List) Front() *Element  // 第一個元素
    func (l *List) Init() *List  // 連結清單初始化
    func (l *List) InsertAfter(v interface{}, mark *Element) *Element // 在某個元素後插入
    func (l *List) InsertBefore(v interface{}, mark *Element) *Element  // 在某個元素前插入
    func (l *List) Len() int // 在連結清單長度
    func (l *List) MoveAfter(e, mark *Element)  // 把e元素移動到mark之後
    func (l *List) MoveBefore(e, mark *Element)  // 把e元素移動到mark之前
    func (l *List) MoveToBack(e *Element) // 把e元素移動到隊列最後
    func (l *List) MoveToFront(e *Element) // 把e元素移動到隊列最頭部
    func (l *List) PushBack(v interface{}) *Element  // 在隊列最後插入元素
    func (l *List) PushBackList(other *List)  // 在隊列最後插入接上新隊列
    func (l *List) PushFront(v interface{}) *Element  // 在隊列頭部插入元素
    func (l *List) PushFrontList(other *List) // 在隊列頭部插入接上新隊列
    func (l *List) Remove(e *Element) interface{} // 删除某個元素      

舉例

func listTest() {
    queue := list.New()
    queue.PushBack(1)
    queue.PushBack(2)
    fmt.Println(queue.Front())
    fmt.Println(queue.Front().Value)
    fmt.Println(queue.Front().Next().Value)
    fmt.Println(queue.Back().Value)
    fmt.Println(queue.Len())
    queue.PushFront(0)
    fmt.Println(queue)

    queue2 := list.New()
    queue2.PushBack(8)
    queue2.PushBack(9)

    queue3 := list.New()
    queue2.PushBack(-1)

    queue.PushBackList(queue2)
    queue.PushFrontList(queue3)

    fmt.Println(queue.Len())
    queue.Remove(queue.Front())
    fmt.Println(queue.Len())

    queue.InsertBefore(100, queue.Front())
    queue.MoveAfter(queue.Front(), queue.Front().Next())

}