Repository navigation
Expand file tree
/
Copy pathlinked_list.go
More file actions
154 lines (135 loc) · 2.29 KB
/
Copy pathlinked_list.go
File metadata and controls
154 lines (135 loc) · 2.29 KB
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
154
package linkedlist
type Node[T comparable] struct {
Data T
Next *Node[T]
}
type LinkedList[T comparable] struct {
head *Node[T]
count int
}
func Constructor[T comparable] () *LinkedList[T] {
return &LinkedList[T]{
head: nil,
count: 0,
}
}
func (ll *LinkedList[T]) Count() int {
return ll.count
}
func (ll *LinkedList[T]) GetFirst() *Node[T] {
return ll.head
}
func (ll *LinkedList[T]) GetLast() *Node[T] {
if(ll.head == nil) {
return nil
}
node := ll.head
for node.Next != nil {
node = node.Next
}
return node
}
func (ll *LinkedList[T]) GetAt(index int) *Node[T] {
if(index < 0 || index >= ll.count) {
return nil
}
node := ll.head
for i := 0; i < index; i++ {
node = node.Next
}
return node
}
func (ll *LinkedList[T]) Contains(value T) bool {
node := ll.head
for node != nil {
if node.Data == value {
return true
}
node = node.Next
}
return false
}
func (ll *LinkedList[T]) Clear() {
ll.head = nil
ll.count = 0
}
func (ll *LinkedList[T]) InsertFirst(value T) {
newNode := &Node[T]{
Data: value,
Next: nil,
}
newNode.Next = ll.head
ll.head = newNode
ll.count++
}
func (ll *LinkedList[T]) InsertLast(value T) {
lastNode:= ll.GetLast()
newNode := &Node[T]{
Data: value,
Next: nil,
}
if(lastNode == nil) {
ll.head = newNode
} else {
lastNode.Next = newNode
}
ll.count++
}
func (ll *LinkedList[T]) InsertAt(value T, index int) {
if(index < 0 || index > ll.count) {
return
}
if(index == 0) {
ll.InsertFirst(value)
return
}
current := ll.head
for range index - 1 {
current = current.Next
}
newNode := &Node[T]{
Data: value,
Next: nil,
}
newNode.Next = current.Next
current.Next = newNode
ll.count++
}
func (ll *LinkedList[T]) RemoveFirst() {
if(ll.head == nil) {
return
}
ll.head = ll.head.Next
ll.count--
}
func (ll *LinkedList[T]) RemoveLast() {
if(ll.head == nil) {
return
}
if(ll.head.Next == nil) {
ll.head = nil
ll.count--
return
}
current := ll.head
for current.Next.Next != nil {
current = current.Next
}
current.Next = nil
ll.count--
}
func (ll *LinkedList[T]) RemoveAt(index int) {
if(index < 0 || index >= ll.count) {
return
}
if(index == 0) {
ll.RemoveFirst()
return
}
current := ll.head
for range index - 1 {
current = current.Next
}
current.Next = current.Next.Next
ll.count--
}