用数组实现的堆栈,

另一种,是用链表实现的堆栈,

在各种不同的编程语言上,

实现都是类似的。

StackArray.go
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
}

  

StackArray_test.go
package StackArray

import (
	"fmt"
	"math/rand"
	"testing"
	"time"
)

func TestStackArray(t *testing.T) {
	//array := [...]int{0,0,0,0,0,0,0,0,0,0}
	var array [arraySize]int

	stackArray := &Stack{
		top:  0,
		data: array,
	}
	fmt.Println(stackArray.top, stackArray.data)

	random := rand.New(rand.NewSource(time.Now().UnixNano()))
	randNumber := random.Intn(100)
	stackArray.Push(randNumber)
	stackArray.Push(random.Intn(100))
	stackArray.Push(random.Intn(100))
	stackArray.Push(random.Intn(100))
	fmt.Println(stackArray.top, stackArray.data)
	retResult, retBool := stackArray.Pop()
	if retBool == true {
		fmt.Println(retResult)
	}
	stackArray.Empty()

	if stackArray.IsEmpty() == false {
		t.Fail()
	}

}

  

输出:
D:/Go/bin/go.exe test -v [D:/go-project/src/StackArray]
=== RUN   TestStackArray
0 [0 0 0 0 0 0 0 0 0 0]
4 [26 2 96 90 0 0 0 0 0 0]
90
--- PASS: TestStackArray (0.00s)
PASS
ok  	StackArray	2.043s
成功: 进程退出代码 0.