這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
今天用Go實現了一個Stack, 提供了如下方法:
//放入元素func (stack *Stack)Push(value ...interface{})//返回下一個元素func (stack *Stack)Top()(value interface{})//返回下一個元素,並從Stack移除元素func (stack *Stack)Pop()(err error)//交換Stackfunc (stack *Stack)Swap(other *Stack)//修改指定索引的元素func (stack *Stack)Set(idx int,value interface{})(err error)//返回指定索引的元素func (stack *Stack)Get(idx int)(value interface{})//是否為空白func (stack *Stack)Empty()(bool)//列印func (stack *Stack)Print()
測試代碼:
package main//Stack//author:Xiong Chuan Liang//date:2015-1-30import ("fmt""github.com/xcltapestry/xclpkg/algorithm" )func main(){stack := algorithm.NewStack()if stack.Empty() {fmt.Println("Stack為空白! ")}else{fmt.Println("Stack不為空白! ",stack.Size())}stack.Push(10)stack.Push(20)stack.Push(30)stack.Push(40)fmt.Println("當前Size() = ",stack.Size())stack.Print()fmt.Println("當前Top() = ",stack.Top())stack.Pop()fmt.Println("執行完Pop()後的Top() = ",stack.Top())stack.Print()stack.Set(2,900)fmt.Println("\n執行完Set(2,900)後的Stack") stack.Print()fmt.Println("\nGet()查看指定的元素: ")fmt.Println("當前idx為1的元素 = ",stack.Get(1))fmt.Println("當前idx為2的元素 = ",stack.Get(2))stack2 := algorithm.NewStack()stack2.Push("111")stack2.Push("222")fmt.Println("\nstack2的初始內容:")stack2.Print()stack.Swap(stack2)fmt.Println("Swap()後stack的內容:")stack.Print()fmt.Println("Swap()後stack2的內容:")stack2.Print()fmt.Println("\nstack增加字串元素: ")stack.Push("中文元素")stack.Push("elem1")stack.Print()}
運行效果:
Stack為空白!當前Size() = 43 => 402 => 301 => 200 => 10當前Top() = 40執行完Pop()後的Top() = 302 => 301 => 200 => 10執行完Set(2,900)後的Stack2 => 9001 => 200 => 10Get()查看指定的元素:當前idx為1的元素 = 20當前idx為2的元素 = 900stack2的初始內容:1 => 2220 => 111Swap()後stack的內容:1 => 2220 => 111Swap()後stack2的內容:2 => 9001 => 200 => 10stack增加字串元素:3 => elem12 => 中文元素1 => 2220 => 111
實現代碼放在Github上 : https://github.com/xcltapestry/xclpkg/blob/master/algorithm/stack.go
C++ STL的stack相關可查: http://www.cplusplus.com/reference/stack/stack/stack/
MAIL: xcl_168@aliyun.com
BLOG: http://blog.csdn.net/xcl168