-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.go
More file actions
64 lines (49 loc) · 1.1 KB
/
stack.go
File metadata and controls
64 lines (49 loc) · 1.1 KB
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
package stack
import "sync"
// Stack defines a thread safe stack
type Stack struct {
mutex sync.Mutex
elements []interface{}
}
// New initialises a new Stack
func New() *Stack {
return &Stack{
elements: make([]interface{}, 0),
}
}
// Peek returns the element at the top of the stack
func (s *Stack) Peek() interface{} {
s.mutex.Lock()
defer s.mutex.Unlock()
if len(s.elements) == 0 {
return nil
}
return s.elements[len(s.elements)-1]
}
// Push adds elements to the stack
func (s *Stack) Push(elements ...interface{}) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.elements = append(s.elements, elements...)
}
// Size returns the total number of elements in the stack
func (s *Stack) Size() int {
s.mutex.Lock()
defer s.mutex.Unlock()
return len(s.elements)
}
// Pop returns the top element and nil if the stack is empty
func (s *Stack) Pop() interface{} {
s.mutex.Lock()
defer s.mutex.Unlock()
if len(s.elements) == 0 {
return nil
}
var (
topIndex = len(s.elements) - 1
element = s.elements[topIndex]
)
s.elements[topIndex] = nil
s.elements = s.elements[:topIndex]
return element
}