-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path10-a.py
More file actions
46 lines (35 loc) · 1013 Bytes
/
Copy path10-a.py
File metadata and controls
46 lines (35 loc) · 1013 Bytes
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
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def insert_in_middle(self, prev_node, new_data):
if prev_node is None:
print("The given previous node must be in the linked list.")
return
new_node = Node(new_data)
new_node.next = prev_node.next
prev_node.next = new_node
def print_list(self):
temp = self.head
while temp:
print(temp.data, end=" ")
temp = temp.next
# create a linked list
llist = LinkedList()
llist.push(4)
llist.push(3)
llist.push(2)
llist.push(1)
print("Original linked list:")
llist.print_list()
# insert a new node in the middle
llist.insert_in_middle(llist.head.next, 5)
print("\nLinked list after inserting a new node:")
llist.print_list()