Leetcode Solution: #1669 Merge In Between Linked Lists 🚀

Rmag Breaking News

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;
}
};

Follow roshan_earth286 for More! ✌️

Leave a Reply

Your email address will not be published. Required fields are marked *