-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcycle_list.go
89 lines (81 loc) · 1.32 KB
/
cycle_list.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
77
78
79
80
81
82
83
84
85
86
87
88
89
package linked_list
import (
"sync"
)
type CycleNode struct {
Data interface{}
Next *CycleNode
}
type CycleList struct {
Size int
Mu *sync.Mutex
Head *CycleNode
}
func NewCycleList() *CycleList {
return &CycleList{
Size: 0,
Mu: new(sync.Mutex),
Head: nil,
}
}
func (l *CycleList) Append(node *CycleNode) bool {
if node == nil {
return false
}
l.Mu.Lock()
defer l.Mu.Unlock()
if l.Size == 0 {
l.Head = node
} else {
old := l.Head
//找到尾部
for {
if old.Next == l.Head {
break
}
old = old.Next
}
old.Next = node
}
node.Next = l.Head //新添加上的链接上头部
l.Size++
return true
}
func (l *CycleList) GetAll() []interface{} {
var data []interface{}
old := l.Head
for {
data = append(data, old.Data)
//当前的下一个节点是头部认为到了尾部
if old.Next == l.Head {
break
}
old = old.Next
}
return data
}
func (l *CycleList) Get(i int) *CycleNode {
if i < 0 || i >= l.Size {
return nil
}
old := l.Head
for j := 0; j < i; j++ {
old = old.Next
}
return old
}
func (l *CycleList) Remove(node *CycleNode) bool {
if node == nil {
return false
}
//找到该节点
old := l.Head
for {
if old.Next == node { //找到该节点前一个节点
break
}
old = old.Next
}
old.Next = node.Next //去掉node的数据
return true
}