-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack_linkedlist.go
76 lines (69 loc) · 1.24 KB
/
stack_linkedlist.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
67
68
69
70
71
72
73
74
75
76
package algorithm
import "fmt"
// 链式栈
type LinkedListStack struct {
bottom *StackNode // 栈底
top *StackNode // 栈顶
}
type StackNode struct {
data interface{}
next *StackNode
}
func NewLinkedListStack() *LinkedListStack {
return &LinkedListStack{
bottom: nil,
top: nil,
}
}
// 入栈
func (obj *LinkedListStack) Push(v interface{}) {
newNode := &StackNode{
data: v,
next: nil,
}
// 空栈
if obj.top == nil {
obj.bottom = newNode
obj.top = newNode
return
}
obj.top.next = newNode
obj.top = newNode
}
// 出栈
func (obj *LinkedListStack) Pop() (interface{}, bool) {
if obj.top == nil {
return nil, false
}
val := obj.top.data
// 有且仅有一个节点
if obj.bottom == obj.top {
obj.bottom = nil
obj.top = nil
return val, true
}
// 查找“栈顶”前一个节点
current := obj.bottom
for current.next != obj.top {
current = current.next
}
current.next = nil
obj.top = current
return val, true
}
// 打印栈
func (obj *LinkedListStack) Print() string {
if obj.bottom == nil {
return ""
}
current := obj.bottom
var message string
for current != nil {
message += fmt.Sprintf("%+v", current.data)
current = current.next
if current != nil {
message += "->"
}
}
return message
}