NOTE

2.6 stack

A last-in-first-out stack.

Data Structures & AlgorithmsCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What It Is

  • Last in, first out

1.1. Data Structure

  • Dynamic array or linked list

1.2. API

type IStack interface {
	// Print all elements
	String() string
	// Get number of elements
	Length() int
	// Whether it is empty
	IsEmpty() bool
	// Push an element onto the top of the stack, O(1)
	Push(e model.Comparable) error
	// Pop an element from the top of the stack, O(1)
	Pop() (model.Comparable, error)
	// Get the top element, O(1)
	Peek() (model.Comparable, error)
}

2. Implementation


type Stack struct {
	array array.IArray
}

func (s *Stack) String() string {
	str := fmt.Sprintf("length=%v, data=[", s.Length())
	for i := 0; i < s.Length(); i++ {
		value, _ := s.array.Get(i)
		str += fmt.Sprintf("%v ", value)
	}
	str = strings.TrimRight(str, " ")
	str += "]"
	return str
}

func NewStack() *Stack {
	return &Stack{array: array.NewArray()}
}

func (s *Stack) Length() int {
	return s.array.Length()
}

func (s *Stack) IsEmpty() bool {
	return s.array.IsEmpty()
}

func (s *Stack) Push(e model.Comparable) error {
	return s.array.AddLast(e)
}

func (s *Stack) Pop() (model.Comparable, error) {
	return s.array.RemoveLast()
}

func (s *Stack) Peek() (model.Comparable, error) {
	return s.array.GetLast()
}

2.1. Test

func TestStack(t *testing.T) {
	stack := NewStack()
	fmt.Println(stack)

	e1 := model.NewElement(1)
	e2 := model.NewElement(2)
	e3 := model.NewElement(3)
	stack.Push(e1)
	stack.Push(e2)
	stack.Push(e3)
	fmt.Println(stack)

	fmt.Println(stack.Pop())
	fmt.Println(stack.Pop())

	fmt.Println(stack.Peek())
	fmt.Println(stack)
}

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub