Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to insert new element into a linked list before the given position in Python
Inserting a new element into a linked list at a specific position is a common operation in data structures. This involves creating a new node and adjusting the links between existing nodes to maintain the list structure.
So, if the input is like nums = [1,5,3,6,8] pos = 3 val = 7, then the output will be [1,5,3,7,6,8].
Algorithm
To solve this, we will follow these steps −
new := create a linked list node with value same as val
-
if pos is same as 0, then
next of new := list_head
return new
temp := list_head
-
while temp is not null and pos is not same as 1, do
temp := next of temp
pos := pos - 1
next of new := next of temp
next of temp := new
return list_head
Implementation
Let us see the following implementation to get better understanding −
class ListNode:
def __init__(self, data, next=None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
def print_list(head):
ptr = head
result = []
while ptr:
result.append(str(ptr.val))
ptr = ptr.next
return '[' + ', '.join(result) + ']'
def solve(list_head, pos, val):
new = ListNode(val)
if pos == 0:
new.next = list_head
return new
temp = list_head
while temp and pos != 1:
temp = temp.next
pos -= 1
new.next = temp.next
temp.next = new
return list_head
# Example usage
nums = [1, 5, 3, 6, 8]
pos = 3
val = 7
list_head = make_list(nums)
list_head = solve(list_head, pos, val)
print(print_list(list_head))
[1, 5, 3, 7, 6, 8]
How It Works
The algorithm works by traversing the linked list until we reach the position where we need to insert the new element. We maintain a pointer that stops at the node just before the insertion point, then adjust the next pointers to include the new node in the chain.
Key Points
For position 0, we insert at the beginning and update the head
For other positions, we traverse to position-1 and insert the new node
The new node's next pointer points to the current node at that position
The previous node's next pointer points to the new node
Conclusion
Inserting elements into a linked list requires careful manipulation of next pointers. The key is to find the correct position and update the links to maintain the list structure while preserving all existing elements.
