Insert a linked list into another linked list
Given two linked lists, list1 and list2 of sizes m and n respectively. The task is to remove list1’s nodes from the ath node to the bth node and insert the list2 in their place.
Input: list1: 10->11->12->13->14->15, list2: 100->101->102->103, a = 3, b = 4
Explanation: Remove the nodes from 3rd index till 4th index (0-based) from list1 and insert list2 at their place.
Input: list1: 1->2, list2: 3->4, a = 0, b = 1
Approach: The task can be solved using simple iteration over the lists. Follow the below steps to solve the problem:
- Start iterating over the linked list1 until the ath node
- Now here take another variable and store the address of (a+1)th node of the list1 and link ath node to the list2 and then iterate over the list2 until the last node and just stop there
- Iterate from (a+1)th node to the bth node of the list1 and then link the last node of the list2 to the (b+1) node of the list1.
- Return the head node of the list1 and then print the whole list1 which will be the expected output.
Below is the implementation of the above approach:
10 11 12 100 101 102 103 15
Time Complexity: O(m+n), n is the length of list1 and m is the length of list2
Auxiliary Space: O(1)
My Personal Notes arrow_drop_up
Please Login to comment...