-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdelete_middle.py
45 lines (36 loc) · 1.04 KB
/
delete_middle.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
from shared.linked_list import Node, LinkedList
def delete_middle(linked_: LinkedList, k: int):
"""
Delete kth node from linked list
Parameters:
linked_ (LinkedList): a Linked List
k (int): the kth position
"""
if k > len(linked_):
return
count = 0
current = linked_.node
while current.next is not None:
if (k - 1) == count:
prev = current
prev.next = current.next.next
current = current.next
count += 1
if __name__ == "__main__":
linked = LinkedList()
linked.add(Node(0))
linked.add(Node(1))
linked.add(Node(2))
linked.add(Node(3))
linked.add(Node(4))
linked.add(Node(5))
linked.add(Node(6))
linked.add(Node(7))
linked.add(Node(8))
linked.add(Node(9))
original_length = len(linked)
delete_middle(linked, 4)
assert original_length - 1 == len(linked)
expected_data_ = [i for i in range(0, 10) if i != 4]
for [node, num] in zip(linked, expected_data_):
assert node.data == num