
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 list.
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]
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
Let us see the following implementation to get better understanding −
Example
Source Code (Python): 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 print('[', end = "") while ptr: print(ptr.val, end = ", ") ptr = ptr.next print(']') class Solution: def solve(self, l1, l2): ans = l1 while l2: if ans: if ans.next != None: newnode = ListNode(l2.val, None) newnode.next = ans.next ans.next = newnode ans = newnode.next l2 = l2.next else: ans.next = l2 break else: return l2 return l1 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)
Input
[5,4,6,3,4,7],[8,6,9]
Output
[5, 8, 4, 6, 6, 9, 3, 4, 7, ]
Advertisements