今天用Go实现了一个Stack, 提供了如下方法:
//放入元素 func (stack *Stack)Push(value ...interface{}) //返回下一个元素 func (stack *Stack)Top()(value interface{}) //返回下一个元素,并从Stack移除元素 func (stack *Stack)Pop()(err error) //交换Stack func (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-30 import ( "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() = 4 3 => 40 2 => 30 1 => 20 0 => 10 当前Top() = 40 执行完Pop()后的Top() = 30 2 => 30 1 => 20 0 => 10 执行完Set(2,900)后的Stack 2 => 900 1 => 20 0 => 10 Get()查看指定的元素: 当前idx为1的元素 = 20 当前idx为2的元素 = 900 stack2的初始内容: 1 => 222 0 => 111 Swap()后stack的内容: 1 => 222 0 => 111 Swap()后stack2的内容: 2 => 900 1 => 20 0 => 10 stack增加字符串元素: 3 => elem1 2 => 中文元素 1 => 222 0 => 111
C++ STL的stack相关可查: http://www.cplusplus.com/reference/stack/stack/stack/
MAIL: xcl_168@aliyun.com
BLOG: http://blog.csdn.net/xcl168
有疑问加站长微信联系(非本文作者)