generated from OtusGolang/home_work
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.go
113 lines (91 loc) · 1.49 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
109
110
111
112
113
package hw04lrucache
type List interface {
Len() int
Front() *ListItem
Back() *ListItem
PushFront(v interface{}) *ListItem
PushBack(v interface{}) *ListItem
Remove(i *ListItem)
MoveToFront(i *ListItem)
}
type ListItem struct {
Value interface{}
Next *ListItem
Prev *ListItem
}
type list struct {
first *ListItem
last *ListItem
count int
}
func NewList() List {
return new(list)
}
func (l *list) Len() int {
return l.count
}
func (l *list) Front() *ListItem {
return l.first
}
func (l *list) Back() *ListItem {
return l.last
}
func (l *list) PushFront(v interface{}) *ListItem {
elem := new(ListItem)
elem.Value = v
elem.Next = l.first
if l.first != nil {
l.first.Prev = elem
}
l.first = elem
if l.last == nil {
l.last = elem
}
l.count++
return elem
}
func (l *list) PushBack(v interface{}) *ListItem {
elem := new(ListItem)
elem.Value = v
elem.Prev = l.last
if l.last != nil {
l.last.Next = elem
}
l.last = elem
if l.first == nil {
l.first = elem
}
l.count++
return elem
}
func (l *list) Remove(i *ListItem) {
if i.Prev == nil {
l.first = i.Next
}
if i.Next == nil {
l.last = i.Prev
}
if i.Prev != nil {
i.Prev.Next = i.Next
}
if i.Next != nil {
i.Next.Prev = nil
}
l.count--
}
func (l *list) MoveToFront(i *ListItem) {
if i.Prev == nil {
// It's already at front
return
}
i.Prev.Next = i.Next
if i.Next == nil {
// Last element
l.last = i.Prev
} else {
i.Next.Prev = i.Prev
}
i.Next = l.first
i.Prev = nil
l.first = i
}