分享
  1. 首页
  2. 文章

Go语言实现堆栈(Stack)

xcltapestry · · 5931 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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





有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:xcltapestry

查看原文:Go语言实现堆栈(Stack)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
5931 次点击
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏