-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertion at specific position in LL
More file actions
46 lines (37 loc) · 1.05 KB
/
insertion at specific position in LL
File metadata and controls
46 lines (37 loc) · 1.05 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
# Define the Node class if not already defined
class Node:
def _init_(self, data):
self.data = data
self.next = None
# Function to insert at a specific position
def insert_at_position(head, value, position):
new_node = Node(value)
if position == 1:
new_node.next = head
return new_node
current = head
for i in range(1, position - 1):
if current is None:
print("Invalid position")
return head
current = current.next
if current is None:
print("Invalid position")
return head
new_node.next = current.next
current.next = new_node
return head
# Optional: Function to print the linked list
def print_linked_list(head):
current = head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
# Example usage
# Assuming you already have a linked list starting with 'head'
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head = insert_at_position(head, 888, 4)
print_linked_list(head)