-
Notifications
You must be signed in to change notification settings - Fork 36
/
lifo.go
66 lines (57 loc) · 1.1 KB
/
lifo.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package jsonql
import (
"fmt"
)
// Lifo - last in first out stack
type Lifo struct {
top *Element
size int
}
// Element - an item in the stack
type Element struct {
value interface{}
next *Element
}
// Stack - a set of functions of the Stack
type Stack interface {
Len() int
Push(value interface{})
Pop() (value interface{})
Peep() (value interface{})
Print()
}
// Len - gets the length of the stack.
func (s *Lifo) Len() int {
return s.size
}
// Push - pushes the value into the stack.
func (s *Lifo) Push(value interface{}) {
s.top = &Element{value, s.top}
s.size++
}
// Pop - pops the last value out of the stack.
func (s *Lifo) Pop() (value interface{}) {
if s.size > 0 {
value, s.top = s.top.value, s.top.next
s.size--
return
}
return nil
}
// Peep - gets the last value in the stack without popping it out.
func (s *Lifo) Peep() (value interface{}) {
if s.size > 0 {
value = s.top.value
return
}
return nil
}
// Print - shows what's in the stack.
func (s *Lifo) Print() {
tmp := s.top
for i := 0; i < s.Len(); i++ {
fmt.Print(tmp.value, ", ")
tmp = tmp.next
}
fmt.Println()
}