-
Notifications
You must be signed in to change notification settings - Fork 24
/
linked_list.py
383 lines (287 loc) · 7.89 KB
/
linked_list.py
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
"""next node creation of linked list"""
if self.head is None:
self.head = Node(value)
return
# Move to the tail (the last node)
node = self.head
while node.next:
node = node.next
node.next = Node(value)
return
def print(self):
"""print nodes of the linked list"""
current_node = self.head
while current_node is not None:
print(current_node.value)
current_node = current_node.next
def to_list(self):
"""Returns python list of Linked List"""
out_list = []
node = self.head
while node:
out_list.append(node.value)
node = node.next
return out_list
def to_linked_list(self,array):
"""
appends array elements into linked list
args: array(obj) -> python list
return : None
"""
for i in array:
self.append(i)
def prepend(self, value):
""" Prepend a node to the beginning of the list """
if self.head is None:
self.head = Node(value)
return
new_head = Node(value)
new_head.next = self.head
self.head = new_head
def search(self, value):
""" Search the linked list for a node with the requested value and return the node. """
if self.head is None:
return None
node = self.head
while node:
if node.value == value:
return node
node = node.next
raise ValueError("Value not found in the list.")
def remove(self, value):
""" Delete the first node with the desired data. """
if self.head is None:
return
if self.head.value == value:
self.head = self.head.next
return
node = self.head
while node.next:
if node.next.value == value:
node.next = node.next.next
return
node = node.next
raise ValueError("Value not found in the list.")
def pop(self):
""" Return the first node's value and remove it from the list. """
if self.head is None:
return None
node = self.head
self.head = self.head.next
return node.value
def insert(self, value, pos):
""" Insert value at pos position in the list. If pos is larger than the
length of the list, append to the end of the list. """
# If the list is empty
if self.head is None:
self.head = Node(value)
return
if pos == 0:
self.prepend(value)
return
index = 0
node = self.head
while node.next and index <= pos:
if (pos - 1) == index:
new_node = Node(value)
new_node.next = node.next
node.next = new_node
return
index += 1
node = node.next
else:
self.append(value)
def size(self):
""" Return the size or length of the linked list. """
size = 0
node = self.head
while node:
size += 1
node = node.next
return size
def reverse(self):
"""
Reverse the inputted linked list
Args:
linked_list(obj): Linked List to be reversed
Returns:
obj: Reveresed Linked List
"""
new_list = LinkedList()
prev_node = None
current_node = self.head
while current_node is not None:
new_node = Node(current_node.value)
new_node.next = prev_node
prev_node = new_node
current_node = current_node.next
new_list.head = prev_node
return new_list
def iscircular(self):
"""
Determine wether the Linked List is circular or not
Args:
linked_list(obj): Linked List to be checked
Returns:
bool: Return True if the linked list is circular, return False otherwise
"""
if self.head is None:
return False
slow = self.head
fast = self.head
while fast and fast.next:
# slow pointer moves one node
slow = slow.next
# fast pointer moves two nodes
fast = fast.next.next
if slow == fast:
return True
# If we get to a node where fast doesn't have a next node or doesn't exist itself,
# the list has an end and isn't circular
return False
def swap_nodes(self, position_one, position_two):
"""
:param: head- head of input linked list
:param: `position_one` - indicates position (index) ONE
:param: `position_two` - indicates position (index) TWO
return: head of updated linked list with nodes swapped
"""
# If both the indices are same
if position_one == position_two:
return head
# Helper references
one_previous = None
one_current = None
two_previous = None
two_current = None
current_index = 0
current_node = self.head
new_head = None
# LOOP - find out previous and current node at both the positions (indices)
while current_node is not None:
# Position_one cannot be equal to position_two,
# so either one of them might be equal to the current_index
if current_index == position_one:
one_current = current_node
elif current_index == position_two:
two_current = current_node
break
# If neither of the position_one or position_two are equal to the current_index
if one_current is None:
one_previous = current_node
two_previous = current_node
# increment both the current_index and current_node
current_node = current_node.next
current_index += 1
# Loop ends
'''SWAPPING LOGIC'''
# We have identified the two nodes: one_current & two_current to be swapped,
# Make use of a temporary reference to swap the references
two_previous.next = one_current
temp = one_current.next
one_current.next = two_current.next
two_current.next = temp
# if the node at first index is head of the original linked list
if one_previous is None:
new_head = two_current
else:
one_previous.next = two_current
new_head = self.head
# Swapping logic ends
return new_head
def sort_append(self, value):
"""
Append a value to the Linked List in ascending sorted order
Args:
value(int): Value to add to Linked List
"""
if self.head is None:
self.head = Node(value)
return
if value < self.head.value:
node = Node(value)
node.next = self.head
self.head = node
return
node = self.head
while node.next is not None and value >= node.next.value:
node = node.next
new_node = Node(value)
new_node.next = node.next
node.next = new_node
return None
def sort(self):
"""
returns sorted linkedlist
Args:
None
Returns:
array: Return sorted Linkedlist
"""
sorted_array = []
array = self.to_list()
linked_list = LinkedList()
for value in array:
linked_list.sort_append(value)
# Convert sorted linked list to a normal list/array
node = linked_list.head
while node:
sorted_array.append(node.value)
node = node.next
return linked_list
def skip_i_delete_j(self, i, j):
"""
:param: head - head of linked list
:param: i - first `i` nodes that are to be skipped
:param: j - next `j` nodes that are to be deleted
return - return the updated head of the linked list
"""
'''
The Idea:
Traverse the Linkedist. Make use of two references - `current` and `previous`.
- Skip `i-1` nodes. Keep incrementing the `current`. Mark the `i-1`^th node as `previous`.
- Delete next `j` nodes. Keep incrementing the `current`.
- Connect the `previous.next` to the `current`
'''
# Edge case - Skip 0 nodes (means Delete all nodes)
head = self.head
if i == 0:
return None
# Edge case - Delete 0 nodes
if j == 0:
return head
# Invalid input
if head is None or j < 0 or i < 0:
return head
# Helper references
current = head
previous = None
# Traverse - Loop untill there are Nodes available in the LinkedList
while current:
'''skip (i - 1) nodes'''
for _ in range(i - 1):
if current is None:
return head
current = current.next
previous = current
current = current.next
'''delete next j nodes'''
for _ in range(j):
if current is None:
break
next_node = current.next
current = next_node
'''Connect the `previous.next` to the `current`'''
previous.next = current
# Loop ends
return head
def __repr__(self):
return "LinkedList({})".format((self.to_list()))