forked from ailidani/paxi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.go
52 lines (44 loc) · 890 Bytes
/
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
package lib
// Stack implements the stack data structure backed by single linked list
type Stack struct {
top *stackNode
length int
}
type stackNode struct {
value interface{}
prev *stackNode
}
// NewStack creates a new Stack
func NewStack() *Stack {
return new(Stack)
}
// Len returns the number of items in the stack
func (s *Stack) Len() int {
return s.length
}
// Peek views the top item on the stack
func (s *Stack) Peek() interface{} {
if s.length == 0 {
return nil
}
return s.top.value
}
// Pop the top item of the stack and return it
func (s *Stack) Pop() interface{} {
if s.length == 0 {
return nil
}
n := s.top
s.top = n.prev
s.length--
return n.value
}
// Push a value onto the top of the stack
func (s *Stack) Push(value interface{}) {
n := &stackNode{value, s.top}
s.top = n
s.length++
}
func (s *Stack) Empty() bool {
return s.length == 0
}