Open In App

Insert a linked list into another linked list

Last Updated : 04 Sep, 2024
Comments
Improve
Suggest changes
4 Likes
Like
Report

Given two linked lists, head1 and head2 of sizes m and n respectively. The task is to remove head1's nodes from the ath node to the bth node and insert head2 in their place.

Examples:

Input: a = 3, b = 4
head1: 10 -> 11 -> 12 -> 13 -> 14 -> 15, head2: 100 -> 101 -> 102 -> 103
Output: 10 -> 11 -> 12 -> 100 -> 101 -> 102 -> 103 -> 15

Insert-a-linked-list-into-another-linked-list_1

Explanation: Remove the nodes from 3rd index till 4th index from head1 and insert head2 at their place.

Input: a = 0, b = 1
head1: 1 -> 2 , head2: 3 -> 4
Output: 3 -> 4
Explanation: Remove the nodes from 0th index till 1th index from head1 and insert head2 at their place.

Approach :

The idea is to start traversing from head1 and identify the node at position a - 1 and b. Let prev points to (a-1)th node and curr points to bth node in head1. Now update the pointer as following:

  • Update prev's next to point to head2 node as we need to remove some nodes in head1 after prev.
  • Start traversing head2 until we reach to end, and update the next pointer of the end node of head2 to curr's next. This will remove the node from a to b in head1.
C++
C Java Python C# JavaScript

Output
10 11 12 100 101 102 103 15 

Time Complexity: O(m + n), m is the length of head1 and n is the length of head2.
Auxiliary Space: O(1)


Article Tags :
Practice Tags :

Similar Reads