Stack in Go

栈的实现

package Stack

import (
	"errors"
)

type StackArray interface {
	Size() int
	IsFull() bool
	IsEmpty() bool
	Pop() (interface{}, bool)
	Push(i []interface{}) bool
	Clear()
}

type Stack struct {
	DataStore []interface{}
	Capacity int
	CurrentSize int
}

func NewStack(i int) *Stack{
	stack := new(Stack)
	stack.DataStore = make([]interface{}, 0, i)
	stack.Capacity = i
	stack.CurrentSize = 0
	return stack
}
func (stack *Stack) Size() int {
	return stack.CurrentSize
}
func (stack *Stack) IsFull() bool {
	if stack.CurrentSize == stack.Capacity {
		return true
	}
	return false
}
func (stack *Stack) IsEmpty() bool {
	if stack.CurrentSize == 0 {
		return true
	}
	return false
}
func (stack *Stack) Push(i interface{}) error {
	if stack.IsFull() {
		return errors.New("stack is full")
	}
	stack.DataStore = append(stack.DataStore, i)
	stack.CurrentSize += 1
	return nil
}
func (stack *Stack) Pop() (interface{}, error) {
	if stack.IsEmpty() {
		return nil, errors.New("stack is empty")
	}
	i := stack.DataStore[stack.CurrentSize - 1]
	stack.CurrentSize--
	stack.DataStore = stack.DataStore[:len(stack.DataStore) - 1]
	return i, nil
}
func (stack *Stack) Clear() {
	stack.CurrentSize = 0
	stack.DataStore = stack.DataStore[:0]
}

你可能感兴趣的:(Stack in Go)