This repository was archived by the owner on Oct 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_list.go
89 lines (76 loc) · 1.61 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
package recache
// Doubly linked list with optimized back and front access
type linkedList struct {
front, back *node
}
type node struct {
next, previous *node
// Storing the location of the node instead of an actual *record to reduce
// load on the GC and the amount of information needed to be stored on the
// record itself.
location recordLocation
}
// Prepend record to list. Returns pointer to created node.
func (ll *linkedList) Prepend(loc recordLocation) (n *node) {
n = &node{
location: loc,
}
if ll.front == nil {
// Empty list
ll.front = n
ll.back = n
return
}
ll.front.previous = n
n.next = ll.front
ll.front = n
return
}
// Return last element data. If list is empty ok=false.
func (ll *linkedList) Last() (loc recordLocation, ok bool) {
if ll.back == nil {
return
}
return ll.back.location, true
}
// Move existing node to front of list
func (ll *linkedList) MoveToFront(n *node) {
// Already in front
if ll.front == n {
return
}
// Join neighbouring nodes
if n.previous != nil {
n.previous.next = n.next
if n == ll.back {
ll.back = n.previous
}
}
if n.next != nil {
n.next.previous = n.previous
}
// Insert to front
n.previous = nil
if ll.front != nil {
ll.front.previous = n
}
n.next = ll.front
ll.front = n
}
// Remove node from list
func (ll *linkedList) Remove(n *node) {
// Are both set back to nil, if this was the only node
if n == ll.front {
ll.front = n.next
}
if n == ll.back {
ll.back = n.previous
}
// Join neighbouring nodes
if n.previous != nil {
n.previous.next = n.next
}
if n.next != nil {
n.next.previous = n.previous
}
}