-
Notifications
You must be signed in to change notification settings - Fork 1
/
stack.go
75 lines (59 loc) · 1.32 KB
/
stack.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package datastructures
import (
"errors"
"sync"
)
// ErrEmptyStack is when a stack is unexpectedly empty
var ErrEmptyStack = errors.New("Stack is empty!")
// Stack is a thread-safe version of the stack abstract data type
// using a linked list
type Stack struct {
list *SinglyLinkedList
length int
mu *sync.RWMutex
}
// NewStack makes a Stack
func NewStack() *Stack {
return &Stack{list: &SinglyLinkedList{}, mu: &sync.RWMutex{}}
}
// Push pushes an item onto the top of the stack increasing length by 1
// Time O(1)
func (s *Stack) Push(v interface{}) {
s.mu.Lock()
defer s.mu.Unlock()
s.length++
s.list.Insert(v)
}
// Pop removes and returns the top item of the stack reducing length by 1
// Time O(1)
func (s *Stack) Pop() (interface{}, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.length == 0 {
return nil, ErrEmptyStack
}
s.length--
return s.list.Delete().value, nil
}
// Peek returns the top item of the stack
// Time O(1)
func (s *Stack) Peek() (interface{}, error) {
s.mu.RLock()
defer s.mu.RUnlock()
if s.length == 0 {
return nil, ErrEmptyStack
}
return s.list.Head().value, nil
}
// IsEmpty ...
// Time O(1)
func (s *Stack) IsEmpty() bool {
return s.Len() == 0
}
// Len gives the length of stack
// Time O(1)
func (s *Stack) Len() int {
s.mu.RLock()
defer s.mu.RUnlock()
return s.length
}