-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_list.go
173 lines (147 loc) · 2.36 KB
/
linked_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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package main
const (
FALSE int = 0
TRUE int = 1
OK int = 2
ERROR int = -1
MEMORYFAIL int = -2
)
type ListNode struct {
data *Node
prev *ListNode
next *ListNode
}
type Node struct {
id int
ctr int
loop_cnt int
next_cnt int
successors [20]*ListNode
}
type List ListNode
type node_t Node
func ListInit() *ListNode {
var l ListNode
l.next = &l
l.prev = &l
return &l
}
func (l *ListNode) Empty() bool {
if l.next == l && l.prev == l {
return true
}
return false
}
func (l *ListNode) Length() int {
count := 0
p := l.next
for p != l {
count += 1
p = p.next
}
return count
}
func (l *ListNode) GetPtr(pos int) *ListNode {
p := l
if pos < 0 || pos > l.Length() {
return nil
}
for i := 1; i <= pos; i++ {
p = p.next
}
return p
}
func (l *ListNode) GetElement(pos int) *Node {
i := 1
p := l.next
if pos < 0 || pos > l.Length() {
return nil
}
for (p != l) && (i != pos) {
p = p.next
i += 1
}
if p == l || i > pos {
return nil
}
return p.data
}
func (l *ListNode) GetIdx(pnode *ListNode) int {
idx := 0
p := l
if l == nil {
return ERROR
}
for p != pnode {
p = p.next
idx += 1
}
if p == l {
return ERROR
}
return idx
}
func (l *ListNode) Insert(pos int, node *Node) int {
if (pos < 1) || (pos > l.Length()+1) {
return ERROR
}
p := l.GetPtr(pos - 1)
if p == nil {
return ERROR
}
var tnode ListNode
tnode.data = node
tnode.prev = p
tnode.next = p.next
p.next.prev = &tnode
p.next = &tnode
return OK
}
func (l *ListNode) Append(node *Node) int {
p := l.prev
var tnode ListNode
tnode.data = node
p.next = &tnode
tnode.prev = p
tnode.next = l
l.prev = &tnode
return OK
}
func (l *ListNode) Remove(pos int) int {
if (pos < 1) || (pos > l.Length()+1) {
return ERROR
}
p := l.GetPtr(pos)
p.prev.next = p.next
p.next.prev = p.prev
return OK
}
func SwapNode(low, high *ListNode) {
var tmp *ListNode
tmp = nil
if low.next == high {
low.prev.next = high
high.prev = low.prev
low.prev = high
low.next = high.next
high.next.prev = low
high.next = low
tmp = high
high = low
low = tmp
} else {
low.prev.next = high
low.next.prev = high
high.prev.next = low
high.next.prev = low
tmp = low.prev
low.prev = high.prev
high.prev = tmp
tmp = low.next
low.next = high.next
high.next = tmp
tmp = high
high = low
low = tmp
}
}