blob: d28ae4597f4359e082b2963e1dcc960ffb31ab21 (
plain)
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 diffmatchpatch
import (
"fmt"
)
type Stack struct {
top *Element
size int
}
type Element struct {
value interface{}
next *Element
}
// Len returns the stack's length
func (s *Stack) Len() int {
return s.size
}
// Push appends a new element onto the stack
func (s *Stack) Push(value interface{}) {
s.top = &Element{value, s.top}
s.size++
}
// Pop removes the top element from the stack and return its value
// If the stack is empty, return nil
func (s *Stack) Pop() (value interface{}) {
if s.size > 0 {
value, s.top = s.top.value, s.top.next
s.size--
return
}
return nil
}
// Peek returns the value of the element on the top of the stack
// but don't remove it. If the stack is empty, return nil
func (s *Stack) Peek() (value interface{}) {
if s.size > 0 {
value = s.top.value
return
}
return -1
}
// Clear empties the stack
func (s *Stack) Clear() {
s.top = nil
s.size = 0
}
func main() {
stack := new(Stack)
stack.Push("Things")
stack.Push("and")
stack.Push("Stuff")
for stack.Len() > 0 {
fmt.Printf("%s ", stack.Pop().(string))
}
fmt.Println()
}
|