This repository has been archived by the owner on Sep 29, 2020. It is now read-only.
generated from OtusGolang/home_work
-
Notifications
You must be signed in to change notification settings - Fork 2
/
list.go
112 lines (96 loc) · 1.64 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
package hw04_lru_cache //nolint:golint,stylecheck
// List ...
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 {
len int
frontItem *listItem
backItem *listItem
}
func (l *list) Len() int {
return l.len
}
func (l *list) Front() *listItem {
return l.frontItem
}
func (l *list) Back() *listItem {
return l.backItem
}
func (l *list) PushFront(v interface{}) *listItem {
new := listItem{
Value: v,
Prev: nil,
Next: nil,
}
if l.frontItem != nil {
l.insertBefore(l.frontItem, &new)
} else {
l.backItem = &new
}
l.frontItem = &new
l.len++
return &new
}
func (l *list) PushBack(v interface{}) *listItem {
new := listItem{
Value: v,
Prev: l.backItem,
Next: nil,
}
if l.backItem != nil {
l.backItem.Next = &new
} else {
l.frontItem = &new
}
l.backItem = &new
l.len++
return &new
}
func (l *list) Remove(i *listItem) {
l.pop(i)
l.len--
}
func (l *list) MoveToFront(i *listItem) {
if i.Prev == nil {
return
}
l.insertBefore(l.frontItem, l.pop(i))
l.frontItem = i
}
func (l *list) pop(i *listItem) *listItem {
if i.Prev != nil {
i.Prev.Next = i.Next
} else {
l.frontItem = i.Next
}
if i.Next != nil {
i.Next.Prev = i.Prev
} else {
l.backItem = i.Prev
}
i.Next = nil
i.Prev = nil
return i
}
func (l *list) insertBefore(root *listItem, new *listItem) {
new.Next = root
if root != nil {
root.Prev = new
}
}
// NewList ...
func NewList() List {
return &list{}
}