-
Notifications
You must be signed in to change notification settings - Fork 20
/
list.go
108 lines (96 loc) · 1.53 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
type Node struct {
Val *Gobj
next *Node
prev *Node
}
type ListType struct {
EqualFunc func(a, b *Gobj) bool
}
type List struct {
ListType
head *Node
tail *Node
length int
}
func ListCreate(listType ListType) *List {
var list List
list.ListType = listType
return &list
}
func (list *List) Length() int {
return list.length
}
func (list *List) First() *Node {
return list.head
}
func (list *List) Last() *Node {
return list.tail
}
func (list *List) Find(val *Gobj) *Node {
p := list.head
for p != nil {
if list.EqualFunc(p.Val, val) {
break
}
p = p.next
}
return p
}
func (list *List) Append(val *Gobj) {
var n Node
n.Val = val
if list.head == nil {
list.head = &n
list.tail = &n
} else {
n.prev = list.tail
list.tail.next = &n
list.tail = list.tail.next
}
list.length += 1
}
func (list *List) LPush(val *Gobj) {
var n Node
n.Val = val
if list.head == nil {
list.head = &n
list.tail = &n
} else {
n.next = list.head
list.head.prev = &n
list.head = &n
}
list.length += 1
}
func (list *List) DelNode(n *Node) {
if n == nil {
return
}
if list.head == n {
if n.next != nil {
n.next.prev = nil
}
list.head = n.next
n.next = nil
} else if list.tail == n {
if n.prev != nil {
n.prev.next = nil
}
list.tail = n.prev
n.prev = nil
} else {
if n.prev != nil {
n.prev.next = n.next
}
if n.next != nil {
n.next.prev = n.prev
}
n.prev = nil
n.next = nil
}
list.length -= 1
}
func (list *List) Delete(val *Gobj) {
list.DelNode(list.Find(val))
}