Source

go-play / stack-package / stack.go

Full commit
/* Stack (FIFO) implementation.

Example usage:
	s := stack.New(2)
	s.Push(1)
	s.Push(2)
	fmt.Println(s)
	i, ok := s.Pop()
*/
package stack

import (
	"fmt"
)

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

/* Create new stack with size `size`. */
func New(size int) *Stack {
	return &Stack{
		size:  size,
		count: 0,
		items: make([]int, size),
	}
}

/* Check if stack is full. */
func (stack *Stack) IsFull() bool {
	return stack.Count() == stack.size
}

/* Number of items in stack. */
func (stack *Stack) Count() int {
	return stack.count
}

/* Check if stack is empty. */
func (stack *Stack) IsEmpty() bool {
	return stack.Count() == 0
}

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

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

	return true
}

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

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

	return item, true
}

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