-
Notifications
You must be signed in to change notification settings - Fork 121
/
list.go
57 lines (48 loc) · 824 Bytes
/
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
package ccache
type List[T any] struct {
Head *Node[T]
Tail *Node[T]
}
func NewList[T any]() *List[T] {
return &List[T]{}
}
func (l *List[T]) Remove(node *Node[T]) {
next := node.Next
prev := node.Prev
if next == nil {
l.Tail = node.Prev
} else {
next.Prev = prev
}
if prev == nil {
l.Head = node.Next
} else {
prev.Next = next
}
node.Next = nil
node.Prev = nil
}
func (l *List[T]) MoveToFront(node *Node[T]) {
l.Remove(node)
l.nodeToFront(node)
}
func (l *List[T]) Insert(value T) *Node[T] {
node := &Node[T]{Value: value}
l.nodeToFront(node)
return node
}
func (l *List[T]) nodeToFront(node *Node[T]) {
head := l.Head
l.Head = node
if head == nil {
l.Tail = node
return
}
node.Next = head
head.Prev = node
}
type Node[T any] struct {
Next *Node[T]
Prev *Node[T]
Value T
}