首頁  >  文章  >  後端開發  >  重新學習CS基礎知識-實作佇列

重新學習CS基礎知識-實作佇列

Patricia Arquette
Patricia Arquette原創
2024-10-16 06:10:30413瀏覽

Relearning basics of CS - Implementing Queue

你有沒有站在佇列裡,佇列資料結構也做同樣的事情。當你想在你最喜歡的自助餐廳點餐時,你站在隊伍的最後,然後你就可以繼續排隊並離開。

CS 中的佇列資料結構執行相同的功能。佇列資料結構是先進先出的資料結構。佇列資料結構可以使用兩個基本函數 Enqueue 和 Dequeue 來構建,這兩個函數基本上是添加到列表和從列表中刪除。

現實生活中的例子

在電腦科學的現實世界中,隊列構成了以下軟體組件的支柱

  • 任務調度
  • 事件處理
  • 非同步通訊等

雖然一個簡單且易於視覺化的組件是

  1. 播放清單中歌曲的隊列
  2. 依資料經由網路傳送的順序排列的佇列等

執行

package main

import (
    "fmt"
    "errors"
)

type Queue struct{
    Elements []int
    Size int
}

func (q *Queue) Enqueue(value int){
    if q.GetLength() == q.Size { 
        fmt.Println("Overflow") 
        return
    } 
    q.Elements = append(q.Elements, value) 
}

func (q *Queue) Dequeue() int {
    if q.IsEmpty() { 
        fmt.Println("UnderFlow") 
        return 0
    } 
    element := q.Elements[0] 
    if q.GetLength() == 1 { 
        q.Elements = nil 
        return element 
    } 
    q.Elements = q.Elements[1:] 
    return element
}

func (q *Queue) GetLength() int { 
    return len(q.Elements) 
} 

func (q *Queue) IsEmpty() bool { 
    return len(q.Elements) == 0
} 

func (q *Queue) Peek() (int, error) { 
    if q.IsEmpty() { 
        return 0, errors.New("empty queue") 
    } 
    return q.Elements[0], nil 
} 

複雜

時間複雜度 - 入隊與出隊的 O(1)
空間複雜度 - 入隊與出隊的 O(1)

參考

參考 - https://www.geeksforgeeks.org/queue-in-go-language/

以上是重新學習CS基礎知識-實作佇列的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn