Python Program For Finding Intersection Of Two Sorted Linked Lists
Last Updated :
15 Dec, 2021
Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed.
Example:
Input:
First linked list: 1->2->3->4->6
Second linked list be 2->4->6->8,
Output: 2->4->6.
The elements 2, 4, 6 are common in
both the list so they appear in the
intersection list.
Input:
First linked list: 1->2->3->4->5
Second linked list be 2->3->4,
Output: 2->3->4
The elements 2, 3, 4 are common in
both the list so they appear in the
intersection list.
Method: Using Dummy Node.
Approach:
The idea is to use a temporary dummy node at the start of the result list. The pointer tail always points to the last node in the result list, so new nodes can be added easily. The dummy node initially gives the tail a memory space to point to. This dummy node is efficient, since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either 'a' or 'b' and adding it to the tail. When the given lists are traversed the result is in dummy. next, as the values are allocated from next node of the dummy. If both the elements are equal then remove both and insert the element to the tail. Else remove the smaller element among both the lists.
Below is the implementation of the above approach:
Python3
# Python program to implement
# the above approach
# Link list node
class Node:
def __init__(self):
self.data = 0
self.next = None
''' This solution uses the temporary
dummy to build up the result list '''
def sortedIntersect(a, b):
dummy = Node()
tail = dummy;
dummy.next = None;
''' Once one or the other
list runs out -- we're done '''
while (a != None and b != None):
if (a.data == b.data):
tail.next = push((tail.next),
a.data);
tail = tail.next;
a = a.next;
b = b.next;
# Advance the smaller list
elif(a.data < b.data):
a = a.next;
else:
b = b.next;
return (dummy.next);
''' UTILITY FUNCTIONS '''
''' Function to insert a node at
the beginning of the linked list '''
def push(head_ref, new_data):
# Allocate node
new_node = Node()
# Put in the data
new_node.data = new_data;
# Link the old list off the new node
new_node.next = (head_ref);
# Move the head to point to the
# new node
(head_ref) = new_node;
return head_ref
''' Function to print nodes in
a given linked list '''
def printList(node):
while (node != None):
print(node.data, end = ' ')
node = node.next;
# Driver code
if __name__=='__main__':
# Start with the empty lists
a = None;
b = None;
intersect = None;
''' Let us create the first sorted
linked list to test the functions
Created linked list will be
1.2.3.4.5.6 '''
a = push(a, 6);
a = push(a, 5);
a = push(a, 4);
a = push(a, 3);
a = push(a, 2);
a = push(a, 1);
''' Let us create the second sorted
linked list. Created linked list
will be 2.4.6.8 '''
b = push(b, 8);
b = push(b, 6);
b = push(b, 4);
b = push(b, 2);
# Find the intersection two linked lists
intersect = sortedIntersect(a, b);
print("Linked list containing common items of a & b ");
printList(intersect);
# This code is contributed by rutvik_56.
Output:
Linked list containing common items of a & b
2 4 6
Complexity Analysis:
- Time Complexity: O(m+n) where m and n are number of nodes in first and second linked lists respectively.
Only one traversal of the lists are needed. - Auxiliary Space: O(min(m, n)).
The output list can store at most min(m,n) nodes .
Please refer complete article on
Intersection of two Sorted Linked Lists for more details!
Similar Reads
Python Program For Finding Intersection Point Of Two Linked Lists There are two singly linked lists in a system. By some programming error, the end node of one of the linked list got linked to the second list, forming an inverted Y-shaped list. Write a program to get the point where two linked lists merge. Above diagram shows an example with two linked lists havi
6 min read
Python Program For Insertion Sort In A Singly Linked List We have discussed Insertion Sort for arrays. In this article we are going to discuss Insertion Sort for linked list. Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list. 2) Traverse the given list, do following for every node. ......a) Insert curr
5 min read
Python Program For Finding The Middle Element Of A Given Linked List Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list
4 min read
Python Program For Merge Sort Of Linked Lists Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible. Let the head be the first node of the linked list to be sorted and headRe
6 min read
Python Program For Merge Sort For Doubly Linked List Given a doubly linked list, write a function to sort the doubly linked list in increasing order using merge sort.For example, the following doubly linked list should be changed to 24810 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Merge sort for singly linked l
3 min read