Source

go-play / stack.go

package main

import (
	"fmt"
)

type Stack struct {
	size  int
	count int
	items []int
}

func NewStack(size int) *Stack {
	return &Stack{
		size:  size,
		count: 0,
		items: make([]int, size),
	}
}

func (stack *Stack) IsFull() bool {
	return stack.count == stack.size
}

func (stack *Stack) IsEmpty() bool {
	return stack.count == 0
}

func (stack *Stack) Push(item int) bool {
	if stack.IsFull() {
		return false
	}

	stack.items[stack.count] = item
	stack.count++

	return true
}

func (stack *Stack) Pop() (int, bool) {
	if stack.IsEmpty() {
		return 0, false
	}

	item := stack.items[stack.count-1]
	stack.count--

	return item, true
}

func (stack *Stack) String() string {
	return fmt.Sprintf("%v", stack.items[:stack.count])
}

func main() {
	s := NewStack(2)
	s.Push(1)
	s.Push(2)
	fmt.Println(s)
	i, ok := s.Pop()
	fmt.Println(s)
	fmt.Println(i, ok)
	i, ok = s.Pop()
	fmt.Println(s)
	fmt.Println(i, ok)
	i, ok = s.Pop()
	fmt.Println(s)
	fmt.Println(i, ok)
}