记录golang利用切片实现栈操作,附例子如下//init stack as string type slice,send data of string with space splite//return a stack with datafunc InitWithStringSpliteSpace(stack []string, s string) []s...
记录golang利用切片实现栈操作,附例子如下
//init stack as string type slice,send data of string with space splite
//return a stack with data
func InitWithStringSpliteSpace(stack []string, s string) []string {
for _, v := range strings.Split(s, " ") {
stack = append(stack, v)
}
return stack
}
//push a data on top of stack
//return a stack with data
func PushTop(stack []string, top string) []string {
return append(stack, top)
}
//get top data from a stack
//return top data
func GetTop(stack []string) string {
return stack[len(stack)-1]
}
//get top data from a stack and remove it,pop out stack
//return top data and stack
func GetAndRemoveTop(stack []string) (string, []string) {
return stack[len(stack)-1], stack[:len(stack)-1]
}
//remove top data form a stack
//return stack
func RemoveTop(stack []string) []string {
return stack[:len(stack)-1]
}
//remove index of data form a stack,the index is sort of stack
//return stack
func RemoveIndex(stack []string, i int) []string {
copy(stack[i:], stack[i+1:])
return stack[:len(stack)-1]
}
func main() {
var stack []string
s := "Hello Go Demo Project"
t := "Top"
stack = InitWithStringSpliteSpace(stack, s)
fmt.Println("InitWithStringSpliteSpace stack = ", stack)
stack = PushTop(stack, t)
fmt.Println("PushTop stack = ", stack)
fmt.Println("GetTop top = ", GetTop(stack))
t, stack = GetAndRemoveTop(stack)
fmt.Printf("GetAndRemoveTop stack = %s,top = %s\n", stack, t)
stack = RemoveTop(stack)
fmt.Println("RemoveTop stack = ", stack)
fmt.Println("RemoveIndex stack = ", RemoveIndex(stack, 2))
}
织梦狗教程
本文标题为:golang利用切片实现栈操作,附例子
基础教程推荐
猜你喜欢
- R语言 ggplot2改变柱状图的顺序操作 2022-11-17
- Swift初始化器与可选链的使用方法介绍 2023-07-08
- ruby-on-rails-为使用Rails 4,nginx和乘客的用户设置自定义域 2023-09-21
- R语言绘制折线图实例分析 2022-11-21
- Ruby3多线程并行Ractor使用方法详解 2023-07-23
- 浅析ELF转二进制允许把 Binary 文件加载到任意位置 2023-07-06
- Swift中重写和重载的使用与对比总结 2023-07-05
- R语言-修改(替换)因子变量的元素操作 2022-11-26
- ruby on rails validates 2023-09-22
- win10下使用virtualbox + vagrant配置ruby开发机环境 2023-07-23
