/
stack.go
52 lines (44 loc) · 1.1 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
// Based on Douglas Hall stack implementation in Go : https://gist.github.com/bemasher/1777766
// Modified by Thomas Minier to add synchronized access
package parser
import "sync"
// stack is a synchronized LIFO structure implementated as a Linked-List
type stack struct {
top *stackElement
size int
*sync.Mutex
}
// stackElement is a element in a stack
type stackElement struct {
value interface{} // All types satisfy the empty interface, so we can store anything here.
next *stackElement
}
// newStack creates a new stack
func newStack() *stack {
return &stack{nil, 0, &sync.Mutex{}}
}
// Return the stack's length
func (s *stack) Len() int {
s.Lock()
defer s.Unlock()
return s.size
}
// Push a new element onto the stack
func (s *stack) Push(value interface{}) {
s.Lock()
s.top = &stackElement{value, s.top}
s.size++
s.Unlock()
}
// Remove the top element from the stack and return it's value
// If the stack is empty, return nil
func (s *stack) Pop() (value interface{}) {
s.Lock()
defer s.Unlock()
if s.size > 0 {
value, s.top = s.top.value, s.top.next
s.size--
return
}
return nil
}