The go language implements sequential storage of stacks
- 2020-05-26 09:19:52
- OfStack
This article demonstrates an example of a stack that implements sequential storage in the go language. Share with you for your reference. The details are as follows:
1. sequence.go code is as follows:
////////
// A stack of sequential storage
////////
package sequence
const MAXSIZE = 20
type Stack struct {
Data [MAXSIZE]int // Storage stack element
Top int // Pointing to the top of the stack, always pointing to the top element -1
}
// The pressure of stack
//d: The stack elements
func (s *Stack) Push(d int) bool {
if s.Top+1 > MAXSIZE {
return false
}
s.Data[s.Top+1] = d
s.Top++
return true
}
// Play the stack
func (s *Stack) Pop() int {
if s.Top == -1 {
return 0
}
s.Data[s.Top] = 0
d := s.Data[s.Top]
s.Top--
return d
}
// Take the capacity of the stack
func (s *Stack) GetVol() int {
return len(s.Data)
}
// Take the length of the stack
func (s *Stack) GetLength() int {
c := s.Top + 1
return c
}
2. main.go code is as follows:
package main
import (
"fmt"
"stack/sequence"
)
func main() {
// Initialize the 1 A stack
var s sequence.Stack
s.Top = -1
// Push the 10 An element
for i := 1; i <= 10; i++ {
s.Push(i)
}
fmt.Println(s)
fmt.Println(s.GetVol()) // capacity
fmt.Println(s.GetLength()) // The length of the
// The pop-up 1 An element
s.Pop()
s.Pop()
fmt.Println(s)
fmt.Println(s.GetVol()) // capacity
fmt.Println(s.GetLength()) // The length of the
}
I hope this article has been helpful to you in the programming of Go language.