-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue_linkedlist.go
73 lines (66 loc) · 1.21 KB
/
queue_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
package algorithm
import "fmt"
// 链式队列
type LinkedListQueue struct {
head *QueueNode // head指针,指向队头
tail *QueueNode // tail指针,指向队尾
}
type QueueNode struct {
data interface{}
next *QueueNode
}
func NewLinkedListQueue() *LinkedListQueue {
return &LinkedListQueue{
head: nil,
tail: nil,
}
}
// 入队
func (obj *LinkedListQueue) Enqueue(v interface{}) bool {
newNode := &QueueNode{
data: v,
next: nil,
}
// 空队列
if obj.tail == nil {
obj.head = newNode
obj.tail = newNode
return true
}
// 非空队列
obj.tail.next = newNode
obj.tail = newNode
return true
}
// 出队
func (obj *LinkedListQueue) Dequeue() (interface{}, bool) {
// 队列为空
if obj.head == nil {
return nil, false
}
val := obj.head.data
// 有且仅有一个节点
if obj.head == obj.tail {
obj.head = nil
obj.tail = nil
return val, true
}
obj.head = obj.head.next
return val, true
}
// 打印队列
func (obj *LinkedListQueue) Print() string {
if obj.head == nil {
return ""
}
current := obj.head
var message string
for current != nil {
message += fmt.Sprintf("%+v", current.data)
current = current.next
if current != nil {
message += "->"
}
}
return message
}