stack

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 29, 2023 License: Apache-2.0 Imports: 0 Imported by: 0

README

Go Reference

stack

This is a simple stack implementation in Go.

Installation

go get github.com/ninedraft/stack@latest

Usage


import "github.com/ninedraft/stack"

func main() {
    s := stack.Stack[int]{}
    
    s.Push(1)
    s.Push(2)
    s.Push(3)

    s.PushMany(4, 5, 6)

    fmt.Println(s.Pop()) // 3, true
    fmt.Println(s.Pop()) // 2, true
    fmt.Println(s.Pop()) // 1, true
}

License

Apache License 2.0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Stack

type Stack[E any] []E

Stack is a LIFO data structure. It is not thread-safe. It's backed by a slice, sot it can be used with `slices` package.

To preallocate a stack, use `make`:

st := make(stack.Stack[int], 0, 10)

func (*Stack[E]) Len

func (s *Stack[E]) Len() int

func (*Stack[E]) Peek

func (s *Stack[E]) Peek() (E, bool)

Peek returns the top element from the stack without removing it. If the stack is empty, the returned element is the zero value of the element type and the second return value is false.

func (*Stack[E]) PeekMany

func (s *Stack[E]) PeekMany(dst []E, n int) []E

PeekMany appends the top n elements from the stack to the given slice without removing them. If the stack is empty, the returned slice is the same as the given slice.

func (*Stack[E]) Pop

func (s *Stack[E]) Pop() (E, bool)

Pop removes and returns the top element from the stack. If the stack is empty, the returned element is the zero value of the element type and the second return value is false.

func (*Stack[E]) PopMany

func (s *Stack[E]) PopMany(dst []E, n int) []E

PopMany removes and appends the top n elements from the stack to the given slice. If the stack is empty, the returned slice is the same as the given slice. If the stack has less than n elements, all elements are removed.

Elements are appended to the given slice in the reverse order.

stack{1, 2, 3}.PopMany(nil, 2) => []int{3, 2}, stack{1}

func (*Stack[E]) Push

func (s *Stack[E]) Push(e E)

func (*Stack[E]) PushMany

func (s *Stack[E]) PushMany(e ...E)

PushMany pushes all elements from the given slice to the stack. Order of elements is preserved.

stack{}.PushMany(1, 2, 3) => stack{1, 2, 3}, stack.Peek() == 3

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL