這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
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