
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find linked list intersection from two linked list in Python
Suppose we have two sorted linked lists L1 and L2, we have to make a new sorted linked list which contains the intersection of these two lists.
So, if the input is like L1 = [2, 4, 8] L2 = [3, 4, 8, 10], then the output will be [4, 8, ]
To solve this, we will follow these steps −
- head := a new node with value 0
- cur := head
- while l1 and l2 are not empty, do
- if value of l1 < value of l2, then
- l1 := next of l1
- otherwise when value of l2 < value of l1, then
- l2 := next of l2
- otherwise,
- next of cur := a new node with value same as value of l1
- l1 := next of l1
- l2 := next of l2
- cur := next of cur
- if value of l1 < value of l2, then
- return next of head
Let us see the following implementation to get better understanding −
Example
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): head = cur = ListNode(0) while l1 and l2: if l1.val < l2.val: l1 = l1.next elif l2.val < l1.val: l2 = l2.next else: cur.next = ListNode(l1.val) l1 = l1.next l2 = l2.next cur = cur.next return head.next ob = Solution() L1 = make_list([2, 4, 8]) L2 = make_list([3, 4, 8, 10]) print_list(ob.solve(L1, L2))
Input
[2, 4, 8], [3, 4, 8, 10]
Output
[4, 8, ]
- Related Articles
- Program to find folded list from a given linked list in Python
- Program to interleave list elements from two linked lists in Python
- Python Circular Linked List Program
- Golang program to join two linked list
- Create new linked list from two given linked list with greater element at each node in C++ Program
- Program to reverse a linked list in Python
- C# program to find node in Linked List
- Intersection of Two Linked Lists in Python
- Python program to remove duplicate elements from a Circular Linked List
- Palindrome Linked List in Python
- Reverse Linked List in Python
- Linked List Cycle in Python
- Python Program to Find the Largest Element in a Doubly Linked List
- Golang program to implement linked list
- Golang program to remove elements from the linked list

Advertisements