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 merge in between linked lists in Python
Suppose we have two linked lists L1 and L2 of length m and n respectively, we also have two positions a and b. We have to remove nodes from L1 from a-th node to b-th node and merge L2 in between.
So, if the input is like L1 = [1,5,6,7,1,6,3,9,12] L2 = [5,7,1,6] a = 3 b = 6, then the output will be [1, 5, 6, 5, 7, 1, 6, 9, 12]
Algorithm
To solve this, we will follow these steps ?
- Find the tail of L2 by traversing to the end
- Traverse L1 and identify two key positions:
- end1: node at position (a-1) - the node before removal starts
- start3: node at position (b+1) - the node after removal ends
- Connect end1 to the head of L2
- Connect the tail of L2 to start3
- Return the modified L1
Example
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
print('[' + ', '.join(result) + ']')
def solve(L1, L2, a, b):
# Find tail of L2
head2 = temp = L2
while temp.next:
temp = temp.next
tail2 = temp
# Find connection points in L1
count = 0
temp = L1
end1, start3 = None, None
while temp:
if count == a-1:
end1 = temp
if count == b+1:
start3 = temp
break
temp = temp.next
count += 1
# Connect the lists
end1.next = head2
tail2.next = start3
return L1
# Test the solution
L1 = [1,5,6,7,1,6,3,9,12]
L2 = [5,7,1,6]
a = 3
b = 6
print_list(solve(make_list(L1), make_list(L2), a, b))
[1, 5, 6, 5, 7, 1, 6, 9, 12]
How It Works
The algorithm works by identifying three segments:
- Segment 1: Nodes from index 0 to (a-1) in L1
- Segment 2: All nodes from L2
- Segment 3: Nodes from index (b+1) to end in L1
We connect these segments by adjusting the next pointers: Segment 1 ? Segment 2 ? Segment 3
Conclusion
This approach efficiently merges two linked lists by removing a specific range from the first list and inserting the second list in that position. The time complexity is O(m + n) where m and n are the lengths of the two lists.
