algorithms/fundamentals/stack/stack.go

46 lines
712 B
Go
Raw Normal View History

2021-11-08 20:32:55 +02:00
package stack
2021-12-15 23:43:29 +02:00
type Stack[Item any] interface {
2021-11-08 20:32:55 +02:00
Push(Item)
Pop() Item
Size() int
IsEmpty() bool
}
// We use linked list as internal data structure
// to get O(1) speed for push and pop opeartions
2021-12-15 23:43:29 +02:00
type node[Item any] struct {
2021-11-08 20:32:55 +02:00
item Item
2021-12-15 23:43:29 +02:00
next *node[Item]
2021-11-08 20:32:55 +02:00
}
2021-12-15 23:43:29 +02:00
type stack[OfType any] struct {
2021-11-08 20:32:55 +02:00
size int
2021-12-15 23:43:29 +02:00
head *node[OfType]
2021-11-08 20:32:55 +02:00
}
2021-12-15 23:43:29 +02:00
func NewStack[OfType any]() Stack[OfType] {
return &stack[OfType]{}
2021-11-08 20:32:55 +02:00
}
2021-12-15 23:43:29 +02:00
func (s *stack[Item]) Push(item Item) {
2021-11-08 20:32:55 +02:00
next := s.head
2021-12-15 23:43:29 +02:00
s.head = &node[Item]{item, next}
2021-11-08 20:32:55 +02:00
s.size++
}
2021-12-15 23:43:29 +02:00
func (s *stack[Item]) Pop() Item {
2021-11-08 20:32:55 +02:00
head := s.head
s.head = head.next
s.size--
return head.item
}
2021-12-15 23:43:29 +02:00
func (s *stack[_]) Size() int {
2021-11-08 20:32:55 +02:00
return s.size
}
2021-12-15 23:43:29 +02:00
func (s *stack[_]) IsEmpty() bool {
2021-11-08 20:32:55 +02:00
return s.size == 0
}