generic stack

This commit is contained in:
Gregory 2021-12-15 23:43:29 +02:00
parent 4c42af490b
commit 7de370e3f9
2 changed files with 15 additions and 20 deletions

View file

@ -1,11 +1,6 @@
package stack package stack
// "Generic" item. type Stack[Item any] interface {
// When type parameters will land this type became
// type Item[T any] T
type Item interface{}
type Stack interface {
Push(Item) Push(Item)
Pop() Item Pop() Item
Size() int Size() int
@ -14,37 +9,37 @@ type Stack interface {
// We use linked list as internal data structure // We use linked list as internal data structure
// to get O(1) speed for push and pop opeartions // to get O(1) speed for push and pop opeartions
type node struct { type node[Item any] struct {
item Item item Item
next *node next *node[Item]
} }
type stack struct { type stack[OfType any] struct {
size int size int
head *node head *node[OfType]
} }
func NewStack() Stack { func NewStack[OfType any]() Stack[OfType] {
return &stack{} return &stack[OfType]{}
} }
func (s *stack) Push(item Item) { func (s *stack[Item]) Push(item Item) {
next := s.head next := s.head
s.head = &node{item, next} s.head = &node[Item]{item, next}
s.size++ s.size++
} }
func (s *stack) Pop() Item { func (s *stack[Item]) Pop() Item {
head := s.head head := s.head
s.head = head.next s.head = head.next
s.size-- s.size--
return head.item return head.item
} }
func (s *stack) Size() int { func (s *stack[_]) Size() int {
return s.size return s.size
} }
func (s *stack) IsEmpty() bool { func (s *stack[_]) IsEmpty() bool {
return s.size == 0 return s.size == 0
} }

View file

@ -6,18 +6,18 @@ import (
) )
func TestSimple(t *testing.T) { func TestSimple(t *testing.T) {
stack := NewStack() stack := NewStack[int]()
stack.Push(1) stack.Push(1)
stack.Push(2) stack.Push(2)
if stack.Pop().(int) != 2 { if stack.Pop() != 2 {
log.Fatal("wrong stack value") log.Fatal("wrong stack value")
} }
} }
func TestSize(t *testing.T) { func TestSize(t *testing.T) {
stack := NewStack() stack := NewStack[int]()
if !stack.IsEmpty() { if !stack.IsEmpty() {
log.Fatal("should be empty") log.Fatal("should be empty")