資料結構——Golang實現堆疊
轉載請註明出處 資料結構——Golang實現堆疊

Golang
1. 棧(stack)
棧(stack)在電腦科學中是限定僅在表尾進行插入或刪除操作的線性表。棧是一種資料結構,它按照後進先出的原則儲存資料,先進入的資料被壓入棧底,最後的資料在棧頂,需要讀資料的時候從棧頂開始彈出資料。棧是隻能在某一端插入和刪除的特殊線性表。用桶堆積物品,先堆進來的壓在底下,隨後一件一件往上堆。取走時,只能從上面一件一件取。讀和取都在頂部進行,底部一般是不動的。棧就是一種類似桶堆積物品的資料結構,進行刪除和插入的一端稱棧頂,另一端稱棧底。插入一般稱為進棧,刪除則稱為退棧。 棧也稱為後進先出表。
2. Golang 實現
2.1. 相關結構體
在這裡,我把棧拆分為兩個部分,容器和連結串列,容器用結構體實現,連結串列用單鏈表,當然大家也可以用其他連結串列結構,甚至陣列來實現。
這裡的例子,也是使用單鏈表實現的。
// 棧資訊 type Stack struct { list *SingleList }
2.2. 棧初始化
對 stack
進行簡單的初始化,也即是對於單鏈表的初始化
// Init 初始化棧 func (s *Stack) Init(){ s.list = new(SingleList) s.list.Init() }
2.3. 壓入棧(push)
往棧內插入資料,稱為push,在這裡對於棧的壓入壓出都是對連結串列的表頭處理,當然也可以對錶尾處理,道理都是一樣的
// Push 壓入棧 func (s *Stack)Push(data interface{}) bool { node := &SingleNode{ Data: data, } return s.list.Insert(0, node) }
2.4. 壓出棧(pop)
取出棧頂資料,稱為pop。
// Pop 壓出棧 func (s *Stack)Pop() interface{}{ node := s.list.Get(0) if node != nil { s.list.Delete(0) return node.Data } return nil }
2.5. 檢視棧頂資料(peek)
只檢視棧頂元素,並不取出
// Peek 檢視棧頂元素 func (s *Stack)Peek() interface{}{ node := s.list.Get(0) if node != nil { return node.Data } return nil }
2.6. 棧長度(size)
查詢棧當前元素數量
// Size 獲取棧的長度 func (s *Stack)Size()uint{ return s.list.Size }
3. 單元測試
package dstr import( "testing" ) func TestStack_Init(t *testing.T){ stack := new(Stack) stack.Init() t.Log("stack init success") } func TestStack_Push(t *testing.T){ stack := new(Stack) stack.Init() b := stack.Push(1) if !b { t.Error("stack push failed") return } t.Log("stack push success") data := stack.Peek() var ( ok bool num int ) if num, ok = data.(int); ok && num == 1{ t.Log("stack push and peek success") return } t.Error("stack push success but peek failed") } func TestStack_Pop(t *testing.T){ stack := new(Stack) stack.Init() d1 := stack.Pop() if d1 != nil{ t.Error("empty stack pop error") return } t.Log("empty stack pop success") stack.Push(1) stack.Push(2) stack.Push(3) d2 := stack.Pop() var ( ok bool num int ) if num, ok = d2.(int); ok && num == 3 && stack.Size() == 2{ t.Log("stack pop success") return } t.Error("stack pop failed") } func TestStack_Peek(t *testing.T){ stack := new(Stack) stack.Init() d := stack.Peek() if d == nil { t.Log("empty stack peek success") return } t.Error("empty stack peek fail") }
4. 原始碼
完
轉載請註明出處: 資料結構——Golang實現堆疊