Go 中 Queue 的實現方式

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

需求

隊列的特性較為單一,基本操作即初始化、擷取大小、添加元素、移除元素等。最重要的特性就是滿足先進先出。

實現

接下來還是按照以前的套路,一步一步來分析如何利用Go的文法特性實現Queue這種資料結構。

定義

首先定義每個節點Node結構體,照例Value的實值型別可以是任意類型,節點的前後指標域指標類型為node

type node struct {value interface{}prev *nodenext *node}

繼續定義鏈表結構,定義出頭結點和尾節點的指標,同時定義隊列大小size:

type LinkedQueue struct {head *nodetail *nodesize int}

大小

擷取隊列大小,只需要擷取LinkedQueue中的size大小即可:

func (queue *LinkedQueue) Size() int {return queue.size}

Peek

Peek操作只需要擷取隊列隊頭的元素即可,不用刪除。傳回型別是任意類型,用介面實現即可。另外如果head指標域為nil,則需要用panic拋出異常,一切ok的話,返回隊前端節點的數值即可:

func (queue *LinkedQueue) Peek() interface{} {if queue.head == nil {panic("Empty queue.")}return queue.head.value}

添加

添加操作在隊列中是比較重要的操作,也要區分隊尾節點是否為nil,根據是否為nil,執行不同的串連操作,最後隊列的size要加1,為了不浪費記憶體新增節點的指標變數要置nil:

func (queue *LinkedQueue) Add(value interface{}) {new_node := &node{value, queue.tail, nil}if queue.tail == nil {queue.head = new_nodequeue.tail = new_node} else {queue.tail.next = new_nodequeue.tail = new_node}queue.size++new_node = nil}

移除

隊列的刪除操作也是很簡單,無非是節點的斷開操作。在此之前,需要判斷鏈表的狀態即是否為nil?而後移除的隊列最前端的節點,先用一個新的變數節點儲存隊列前面的節點,進行一系列操作之後,至nil,並將長度減少即可。

func (queue *LinkedQueue) Remove() {if queue.head == nil {panic("Empty queue.")}first_node := queue.headqueue.head = first_node.nextfirst_node.next = nilfirst_node.value = nilqueue.size--first_node = nil}

Ok,以上就是用Go的基本文法特性實現Queue的過程。謝謝閱讀!!!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.