」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 重新學習CS基礎知識-實作佇列

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

發佈於2024-11-09
瀏覽:635

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/

版本聲明 本文轉載於:https://dev.to/abinav_athreya_f4b5487056/relearning-basics-of-cs-implementing-queue-54g7?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3