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 interleave list elements from two linked lists in Python
Suppose we have two linked lists l1 and l2, we have to return one linked list by interleaving elements of these two lists starting with l1. If there are any leftover nodes in a linked list, they should be appended to the result.
So, if the input is like l1 = [5,4,6,3,4,7] l2 = [8,6,9], then the output will be [5,8,4,6,6,9,3,4,7]
Algorithm
To solve this, we will follow these steps ?
ans := l1
-
while l2 is not null, do
-
if ans is not null, then
-
if next of ans is not null, then
newnode := a new list node with same value of l2
next of newnode := next of ans
next of ans := newnode
ans := next of newnode
l2 := next of l2
-
otherwise,
next of ans := l2
come out from the loop
-
otherwise, return l2
-
return l1
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):
if not elements:
return None
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) + ']')
class Solution:
def solve(self, l1, l2):
ans = l1
while l2:
if ans:
if ans.next:
newnode = ListNode(l2.val)
newnode.next = ans.next
ans.next = newnode
ans = newnode.next
l2 = l2.next
else:
ans.next = l2
break
else:
return l2
return l1
# Test the solution
ob = Solution()
l1 = make_list([5, 4, 6, 3, 4, 7])
l2 = make_list([8, 6, 9])
res = ob.solve(l1, l2)
print_list(res)
The output of the above code is ?
[5, 8, 4, 6, 6, 9, 3, 4, 7]
How It Works
The algorithm works by iterating through the first linked list (l1) and inserting nodes from the second list (l2) at alternate positions. When we reach the end of l1, any remaining nodes from l2 are appended directly to maintain the interleaved pattern.
Key Points
The interleaving starts with l1, so the first element is always from l1
New nodes are created for l2 elements to avoid modifying the original l2 structure
If l1 ends before l2, the remaining l2 nodes are appended as-is
The time complexity is O(min(m,n)) where m and n are the lengths of l1 and l2
Conclusion
This approach efficiently interleaves two linked lists by inserting elements from the second list into alternate positions of the first list. The algorithm handles cases where lists have different lengths by appending remaining elements.
