-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_list.py
74 lines (63 loc) · 1.73 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
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, head=None):
self.head = head
def append(self, new_node):
current = self.head
if current:
while current.next:
current = current.next
current.next = new_node
else:
self.head = new_node
def delete(self, value):
current =self.head
if current.value == value:
self.head = current.next
else:
while current.next:
if current.value == value:
break
prev = current
current = current.next
if current is None:
return
prev.next = current.next
current = None
def insert(self, new_element: Node, position: int):
count = 1
if count == position:
new_element.next = self.head.next
self.head = new_element
else:
current = self.head
while current:
if position == count+1:
new_element.next = current.next
current.next = new_element
return
else:
count += 1
current = current.next
def print(self):
current = self.head
while current:
print(current.value)
current = current.next
if __name__ == "__main__":
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
an4 = Node(4)
in5 = Node(3)
ll = LinkedList()
ll.append(n1)
ll.append(n2)
ll.append(n3)
ll.print()
ll.insert(in5, 3)
ll.insert(an4, 1)
ll.print()