Golang 資料結構:棧與隊列

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

Golang 中棧、隊列的實現及常用操作,資料結構系列原文:flaviocopes.com,翻譯已獲作者授權。

概述

棧是資料按照後進先出 LIFO(Last-In-First-Out) 原則組成的集合。添加和移除元素都是在棧頂進行,類比書堆,不能在棧底增刪元素。

棧的應用很廣泛,比如網頁跳轉後一層層返回,ctrl+z 撤銷操作等。

使用 slice 動態類型來實現棧,棧元素的類型是使用 genny 建立的通用類型 ItemStack,實現以下常用操作:

1
2
3
New()// 產生棧的構造器
Push()
Pull()
代碼實現
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package stack

import (
"github.com/cheekybits/genny/generic"
"sync"
)

type Item generic.Type

type ItemStack struct {
items []Item
lock sync.RWMutex
}

// 建立棧
func (s *ItemStack) New() *ItemStack {
s.items = []Item{}
return s
}

// 入棧
func (s *ItemStack) Push(t Item) {
s.lock.Lock()
s.items = append(s.items, t)
s.lock.Unlock()
}

// 出棧
func (s *ItemStack) Pop() *Item {
s.lock.Lock()
item := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1 ]
s.lock.Unlock()
return &item
}

測試案例:stack_test.go

隊列

概述

隊列是資料按照先進先出 FIFO(First-In-First-Out) 原則組成的集合,類比排隊,在隊列任一端添加元素,從對應的另一端刪除元素。

使用 slice 動態類型來實現隊列,元素的類型為通用類型 ItemQueue ,實現以下常用操作:

1
2
3
4
5
6
New()// 產生隊列的構造器
Enqueue()
Dequeue()
Front()
IsEmpty()
Size()
代碼實現
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package queue

import (
"github.com/cheekybits/genny/generic"
"sync"
)

type Item generic.Type

type ItemQueue struct {
items []Item
lock sync.RWMutex
}

// 建立隊列
func (q *ItemQueue) New() *ItemQueue {
q.items = []Item{}
return q
}

// 如隊列
func (q *ItemQueue) Enqueue(t Item) {
q.lock.Lock()
q.items = append(q.items, t)
q.lock.Unlock()
}

// 出隊列
func (q *ItemQueue) Dequeue() *Item {
q.lock.Lock()
item := q.items[0]
q.items = q.items[1:len(q.items)]
q.lock.Unlock()
return &item
}

// 擷取隊列的第一個元素,不移除
func (q *ItemQueue) Front() *Item {
q.lock.Lock()
item := q.items[0]
q.lock.Unlock()
return &item
}

// 判空
func (q *ItemQueue) IsEmpty() bool {
return len(q.items) == 0
}

// 擷取隊列的長度
func (q *ItemQueue) Size() int {
return len(q.items)
}

測試案例:queue_test.go

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.