package StackArray
const arraySize = 10
type Stack struct {
top int
data [arraySize]int
}
func (s *Stack) Push(i int) bool {
if s.top == len(s.data) {
return false
}
s.data[s.top] = i
s.top += 1
return true
}
func (s *Stack) Pop() (int, bool) {
if s.top == 0 {
return 0, false
}
i := s.data[s.top-1]
s.top -= 1
return i, true
}
func (s *Stack) Peek() int {
return s.data[s.top-1]
}
func (s *Stack) Get() []int {
return s.data[:s.top]
}
func (s *Stack) IsEmpty() bool {
return s.top == 0
}
func (s *Stack) Empty() {
s.top = 0
}
package StackArray
import (
"fmt"
"reflect"
"testing"
)
func TestStack(t *testing.T) {
var stack = Stack{0, [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}}
empty := stack.IsEmpty()
if empty {
fmt.Println("isEmpty passed!")
}
fmt.Println(reflect.TypeOf(stack))
push := stack.Push(10)
push = stack.Push(11)
push = stack.Push(12)
push = stack.Push(13)
push = stack.Push(14)
push = stack.Push(15)
push = stack.Push(16)
push = stack.Push(17)
push = stack.Push(18)
push = stack.Push(19)
push = stack.Push(20)
push = stack.Push(21)
push = stack.Push(22)
if !push {
t.Logf(" push passed!")
}
if i, b := stack.Pop(); b {
if i == 19 {
t.Logf("pop passed!")
}
}
get := stack.Get() //[10 11 12 13 14 15 16 17 18]
if len(get) == 9 {
t.Logf("get passed!")
}
peek := stack.Peek()
if 18 == peek {
t.Logf("Peek passed!")
}
get = stack.Get()
if len(get) == 9 {
t.Logf("get passed!")
}
}
网友评论