-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedlist.go
153 lines (116 loc) · 2.16 KB
/
linkedlist.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package collections
import "fmt"
type nodeLinkedList struct {
value interface{}
next *nodeLinkedList
}
type LinkedList struct {
head *nodeLinkedList
tail *nodeLinkedList
size int
}
func (l *LinkedList) IsEmpty() bool {
return l.size == 0
}
func (l *LinkedList) Size() int {
return l.size
}
func (l *LinkedList) InsertAtEnd(value interface{}) {
n := &nodeLinkedList{value, nil}
if l.IsEmpty() {
l.head = n
l.tail = n
} else {
l.tail.next = n
l.tail = n
}
l.size += 1
}
func (l *LinkedList) Push(value interface{}) {
l.InsertAtEnd(value)
}
func (l *LinkedList) InsertAtBeginning(value interface{}) {
n := &nodeLinkedList{value, nil}
if l.IsEmpty() {
l.head = n
l.tail = n
} else {
n.next = l.head
l.head = n
}
l.size += 1
}
func (l *LinkedList) InsertAt(index int, value interface{}) {
if index < 0 || index > l.size {
return
}
if index == 0 {
l.InsertAtBeginning(value)
return
}
if index == l.size {
l.InsertAtEnd(value)
return
}
n := &nodeLinkedList{value, nil}
current := l.head
for i := 0; i < index-1; i++ {
current = current.next
}
n.next = current.next
current.next = n
l.size += 1
}
func (l *LinkedList) RemoveFrom(index int) interface{} {
if index < 0 || index >= l.size {
return nil
}
if index == 0 {
value := l.head.value
l.head = l.head.next
l.size -= 1
return value
}
if index == l.size-1 {
value := l.tail.value
current := l.head
for i := 0; i < index-1; i++ {
current = current.next
}
l.tail = current
l.tail.next = nil
l.size -= 1
return value
}
current := l.head
for i := 0; i < index-1; i++ {
current = current.next
}
value := current.next.value
current.next = current.next.next
l.size -= 1
return value
}
func (l *LinkedList) Pop() interface{} {
return l.RemoveFrom(l.size - 1)
}
func (l *LinkedList) Get(index int) interface{} {
if index < 0 || index >= l.size {
return nil
}
current := l.head
for i := 0; i < index; i++ {
current = current.next
}
return current.value
}
func (l *LinkedList) Clear() {
l.head = nil
l.tail = nil
l.size = 0
}
func (l *LinkedList) Print() {
for n := l.head; n != nil; n = n.next {
fmt.Println(n.value)
}
}