DEV Community

Roshan Sharma
Roshan Sharma

Posted on

Leetcode Solution: #1669 Merge In Between Linked Lists πŸš€

Question Type: Medium 🎚️
Complexities: Time: O(n), Space: O(1) 🚩

Code: πŸ‘‡

class Solution {
 public:
  ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
    ListNode* nodeBeforeA = list1;
    for (int i = 0; i < a - 1; ++i)
      nodeBeforeA = nodeBeforeA->next;

    ListNode* nodeB = nodeBeforeA->next;
    for (int i = 0; i < b - a; ++i)
      nodeB = nodeB->next;

    nodeBeforeA->next = list2;
    ListNode* lastNodeInList2 = list2;

    while (lastNodeInList2->next != nullptr)
      lastNodeInList2 = lastNodeInList2->next;

    lastNodeInList2->next = nodeB->next;
    nodeB->next = nullptr;
    return list1;
  }
};
Enter fullscreen mode Exit fullscreen mode

Follow roshan_earth286 for More! ✌️

Top comments (0)