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.youkuaiyun.com/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]