-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked_list.go
93 lines (75 loc) · 1.23 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
package datt
type node[T any] struct {
value T
next *node[T]
}
type LinkedList[T any] struct {
front *node[T]
back *node[T]
len int
}
func (l *LinkedList[T]) PushFront(v T) {
new := &node[T]{value: v}
if l.len == 0 {
l.front = new
l.back = new
l.len++
return
}
previousFront := l.front
new.next = previousFront
l.front = new
l.len++
}
func (l *LinkedList[T]) PushBack(v T) {
new := &node[T]{value: v}
if l.len == 0 {
l.front = new
l.back = new
l.len++
return
}
previousBack := l.back
previousBack.next = new
l.back = new
l.len++
}
func (l *LinkedList[T]) PopFront() (T, bool) {
if l.len == 0 {
var d T
return d, false
}
if l.len == 1 {
front := l.front
l.front = nil
l.back = nil
l.len--
return front.value, true
}
previous := l.front
l.front = l.front.next
l.len--
return previous.value, true
}
func (l *LinkedList[T]) Front() (T, bool) {
if l.len == 0 {
var d T
return d, false
}
return l.front.value, true
}
func (l *LinkedList[T]) Len() int {
return l.len
}
func (l *LinkedList[T]) Do(f func(v T)) {
current := l.front
for current != nil {
f(current.value)
current = current.next
}
}
func (l *LinkedList[T]) Clear() {
l.len = 0
l.front = nil
l.back = nil
}