gstack

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2024 License: MIT Imports: 3 Imported by: 0

README

gstack

Simple Generic Stack implementation in Go using linked list

Usage

s := gstack.New(1, 2, 3, 4)
fmt.Println(s.Len())
fmt.Println(s.Pop())
fmt.Println(s.Pop())
fmt.Println(s.Pop())
fmt.Println(s.Pop())
s.Push(5)
fmt.Println(s.Peek())
// Output: 4
// 4
// 3
// 2
// 1
// 5

Changelog

v0.1.0
  • minimal supported version of Go is 1.20
  • initial implementation
v1.0.0
  • minimal supported version of Go is 1.23
  • added Iter method to iterate over the stack and consume all items
s := gstack.New(1, 2, 3, 4)
for v := range s.Iter() {
    fmt.Println(v)
}
fmt.Println("len:", s.Len())
// Output: 4
// 3
// 2
// 1
// len: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type GStack

type GStack[T any] struct {
	// contains filtered or unexported fields
}

GStack is generic Stack implementation using linked list

Example
package main

import (
	"fmt"
	"github.com/sv-tools/gstack"
)

func main() {
	s := gstack.New(1, 2, 3, 4)
	fmt.Println(s.Len())
	fmt.Println(s.Pop())
	fmt.Println(s.Pop())
	fmt.Println(s.Pop())
	fmt.Println(s.Pop())
	s.Push(5)
	fmt.Println(s.Peek())
}
Output:

4
4
3
2
1
5

func New

func New[T any](items ...T) GStack[T]

New creates an instance of GStack and pushes all given items to the created stack in reversed order

func (*GStack[T]) Clear

func (s *GStack[T]) Clear()

Clear clears the stack

func (*GStack[T]) Iter added in v1.0.0

func (s *GStack[T]) Iter() iter.Seq[T]

Iter returns a consuming iterator for the stack

Example
package main

import (
	"fmt"
	"github.com/sv-tools/gstack"
)

func main() {
	s := gstack.New(1, 2, 3, 4)
	for v := range s.Iter() {
		fmt.Println(v)
	}
	fmt.Println("len:", s.Len())
}
Output:

4
3
2
1
len: 0

func (*GStack[T]) Len

func (s *GStack[T]) Len() int

Len returns the length of the stack

func (*GStack[T]) Peek

func (s *GStack[T]) Peek() T

Peek returns the top item without removing it or a zero object of given type

func (*GStack[T]) Pop

func (s *GStack[T]) Pop() T

Pop returns the top item and removes it from the stack or returns a zero object of given type

func (*GStack[T]) Push

func (s *GStack[T]) Push(item T)

Push puts the given item into the stack

func (*GStack[T]) String

func (s *GStack[T]) String() string

String returns the list of all items in text format

Jump to

Keyboard shortcuts

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