hi, let Avik connect you.


** You can give your thought about this content and request modifications if needed from Ask For Modifications page. Thank You.

** You can check all the posts on the Posts page.

** More about me in the About Me section.

1669. Merge In Between Linked Lists


  • Approach:

    1. Traverse through LinkedList1.

    2. When reached the Xth position, cut LinkedList1.

    3. Connect the LinkedList2 head as the immediate next node of LinkedList1.

    4. Traverse through the rest of the LinkedList1 nodes.

    5. When reached the next node of Yth position, cut LinkedList1.

    6. Now traverse through the LinkedList2 until reached the end.

    7. Add the currently pointing node of LinkedList1 as the next node of LinkedList2.

    8. Return LinkedList1.


  • Time and Space Complexity:

      • Time Complexity: O(N)

      • Space Complexity: O(1)


Code [C++]

ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {

ListNode * cur1 = list1, *prev1, *prev2;

ListNode * cur2 = list2;

for(int i=0; i<a; i++){

prev1 = cur1;

cur1 = cur1->next;

}

prev1->next = list2;

for(int i=a; i<=b; i++){

cur1 = cur1->next;

}

while(cur2->next){

cur2 = cur2->next;

}

cur2->next = cur1;

return list1;

}