-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.go
More file actions
62 lines (53 loc) · 1.21 KB
/
stack.go
File metadata and controls
62 lines (53 loc) · 1.21 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
package stack
import (
"fmt"
"sync"
)
// Stack represents a LIFO data structure
type Stack struct {
sync sync.RWMutex
elements []interface{}
}
// New creates and returns a new Stack
func New() *Stack {
return &Stack{elements: make([]interface{}, 0)}
}
// Push adds an element to the top of the stack
func (st *Stack) Push(value interface{}) {
st.sync.Lock()
defer st.sync.Unlock()
st.elements = append(st.elements, value)
}
// Pop removes and returns the top element
func (st *Stack) Pop() interface{} {
st.sync.Lock()
defer st.sync.Unlock()
if len(st.elements) == 0 {
return nil
}
l := len(st.elements)
value := st.elements[l-1]
st.elements = st.elements[:l-1]
return value
}
// Peek return the last element from the stack
func (st *Stack) Peek() interface{} {
st.sync.RLock()
defer st.sync.RUnlock()
if len(st.elements) == 0 {
return nil
}
l := len(st.elements)
value := st.elements[l-1]
return value
}
// IsEmpty returns true if the stack has no elements
func (st *Stack) IsEmpty() bool {
return len(st.elements) == 0
}
// String returns a string representation of the stack
func (st *Stack) String() string {
st.sync.RLock()
defer st.sync.RUnlock()
return fmt.Sprintf("Stack%v", st.elements)
}