/
list.go
85 lines (75 loc) · 1.26 KB
/
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
package main
type Node struct {
Val *Obj
Pre *Node
Next *Node
}
type ListType struct {
EqualFn func(*Node, *Node) bool
}
func ListEqualFn(a *Node, b *Node) bool {
if a == nil && b == nil {
return true
} else if a == nil && b != nil {
return false
} else if a != nil && b == nil {
return false
}
// a, b not nil
if a.Val.gType != b.Val.gType {
return false
}
return a.Val.ptr == b.Val.ptr
}
type List struct {
ListType
Head *Node
Tail *Node
len int
}
func NewList(listType ListType) *List {
return &List{ListType: listType}
}
func (l *List) Len() int {
return l.len
}
func (l *List) Add(val *Obj) {
node := &Node{Val: val}
if l.Head == nil {
l.Head = node
l.Tail = node
} else {
node.Pre = l.Tail
l.Tail.Next = node
l.Tail = node
}
l.len++
}
func (l *List) FindByVal(val *Obj) *Node {
node := &Node{Val: val}
for cur := l.Head; cur != nil; cur = cur.Next {
if l.EqualFn(node, cur) {
return cur
}
}
return nil
}
func (l *List) Del(val *Obj) {
if cur := l.FindByVal(val); cur != nil {
pre, next := cur.Pre, cur.Next
if pre == nil {
l.Head = next
} else {
pre.Next = next
}
if next == nil {
l.Tail = pre
} else {
next.Pre = pre
}
cur.Next = nil
cur.Pre = nil
cur.Val.decrRefCount()
l.len--
}
}