forked from ricardolonga/jsongo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
stack.go
49 lines (42 loc) · 904 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
package jsone
// Stack data structure.
type Stack struct {
top *entry
length int
}
// Stack entry data structure.
type entry struct {
stack *Stack
next *entry
value interface{}
}
// NewStack creates a new Stack data structure object.
func NewStack() *Stack {
return &Stack{top: nil, length: 0}
}
// Push a new entry to the stack.
func (s *Stack) Push(value interface{}) {
s.top = &entry{stack: s, next: s.top, value: value}
s.length++
}
// Pop out an entry from the stack.
func (s *Stack) Pop() interface{} {
if s.length > 0 {
value := s.top.value
s.top = s.top.next
s.length--
return value
}
return nil
}
// Top gets the last inserted entry with out deleting from the stack.
func (s *Stack) Top() interface{} {
if s.length > 0 {
return s.top.value
}
return nil
}
// Size returns the number of the elements in the stack.
func (s *Stack) Size() int {
return s.length
}