Go语言实现堆栈(Stack)

     今天用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



实现代码放在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




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值