by Utkarsh Jaiswal
Technology
December 3, 2023
|
6 min read
We explore an efficient approach to merge two sorted linked lists in C++. We leverage a dummy node and maintain a pointer to the current node in the merged list. By iterating through both lists, we compare elements and link nodes in ascending order. We handle remaining elements if one list is longer than the other, ensuring a fully merged and sorted result.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { ListNode* dummy = new ListNode(0); ListNode* current = dummy; while(list1 != nullptr && list2 != nullptr){ if (list1->val <= list2->val) { current->next = list1; list1 = list1->next; } else { current->next = list2; list2 = list2->next; } current = current->next; } // If one of the lists is not empty, append the remaining elements if (list1 != nullptr) { current->next = list1; } else if (list2 != nullptr) { current->next = list2; } // Return the merged list starting from the next of the dummy node return dummy->next; } };