Go入门 - 栈

1. 创建一个固定大小保存证书的栈,它无须超出限制的增长。定义push函数(入栈)和pop函数(出栈)

package main

import "fmt"

//定义一个新的类型来表达栈,需要一个数组和一个指向最后一个元素的索引
type stack struct {
	i int
	data [10]int
}
//注意,Go的数据传递中,是值传递,但是这样不能满足我们的预期。因为一个副本被创建并传递给函数,push和pop处理的都是副本。所以提供指针
func (s *stack) push(k int) {
	if s.i +1 > 10 {
		fmt.Println("I'm full")
		return
	}
	s.data[s.i] = k
	s.i++
}
func (s *stack) pop() int{
	if s.i -1 < 0 {
		fmt.Println("I'm hungry")
		return 0
	}

	s.i--
	result := s.data[s.i]
	s.data[s.i] = 0
	return result
}

func main() {
	var s stack
	s.push(1)
	s.push(11)
	s.push(21)
	s.push(31)
	s.push(41)
	s.push(51)
	s.push(61)
	s.push(71)
	s.push(81)
	s.push(91)
	s.push(101)
	s.push(1011)
	fmt.Printf("Stack %v \n", s)
	x := s.pop()
	fmt.Println("Pop x ", x)
	y := s.pop()
	fmt.Println("Pop y ", y)
	z := s.pop()
	fmt.Println("Pop z ", z)
	fmt.Printf("After pop the Stack is %v \n", s)
	s.push(161)
	fmt.Printf("Stack %v \n", s)
}


打印结果:

I'm full
I'm full
Stack {10 [1 11 21 31 41 51 61 71 81 91]} 
Pop x  91
Pop y  81
Pop z  71
After pop the Stack is {7 [1 11 21 31 41 51 61 0 0 0]} 
Stack {8 [1 11 21 31 41 51 61 161 0 0]}  

推荐阅读 https://blog.csdn.net/NewGirlFriend/article/details/79542517

2.编写一个string方法,将栈转化为字符串形式的表达

package main

import (
	"fmt"
	"strconv"
)

//定义一个新的类型来表达栈,需要一个数组和一个指向最后一个元素的索引
type stack struct {
	i int
	data [10]int
}
//注意,Go的数据传递中,是值传递,但是这样不能满足我们的预期。因为一个副本被创建并传递给函数,push和pop处理的都是副本。所以提供指针
func (s *stack) push(k int) {
	if s.i +1 > 10 {
		fmt.Println("I'm full")
		return
	}
	s.data[s.i] = k
	s.i++
}
func (s *stack) pop() int{
	if s.i -1 < 0 {
		fmt.Println("I'm hungry")
		return 0
	}

	s.i--
	result := s.data[s.i]
	s.data[s.i] = 0
	return result
}

func (s stack) String1() string {
	var str string
	for i :=0; i<=s.i;i++ {
		str = str + "[" +
			strconv.Itoa(i) + ":" + strconv.Itoa(s.data[i]) + "]"
	}
	return str
}

func main() {
	var s stack
	s.push(1)
	s.push(11)
	s.push(21)
	s.push(31)
	s.push(41)
	s.push(51)
	s.push(61)
	s.push(71)
	s.push(81)
	s.push(91)
	s.push(101)
	s.push(1011)
	fmt.Printf("Stack %v \n", s)
	x := s.pop()
	fmt.Println("Pop x ", x)
	y := s.pop()
	fmt.Println("Pop y ", y)
	z := s.pop()
	fmt.Println("Pop z ", z)
	fmt.Printf("After pop the Stack is %v \n", s)
	s.push(161)
	fmt.Printf("Stack %v \n", s)
	fmt.Printf("Stack %v \n", s.String1())

}

打印结果

I'm full
I'm full
Stack {10 [1 11 21 31 41 51 61 71 81 91]} 
Pop x  91
Pop y  81
Pop z  71
After pop the Stack is {7 [1 11 21 31 41 51 61 0 0 0]} 
Stack {8 [1 11 21 31 41 51 61 161 0 0]} 
Stack [0:1][1:11][2:21][3:31][4:41][5:51][6:61][7:161][8:0] 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值