Merge Two Sorted Lists Algorithm

The Merge Two Sorted Lists Algorithm is a fundamental technique in computer programming and data manipulation, particularly in the context of sorting and merging data. It is an efficient and straightforward method for combining two pre-sorted lists into one single, sorted list. This algorithm assumes that the input lists are already sorted in either ascending or descending order and that the goal is to merge them into a new list while preserving the same order. The Merge Two Sorted Lists Algorithm is a crucial part of more advanced sorting algorithms, such as the Merge Sort, and is also used in various other applications, including data analysis, database management, and file merging. The algorithm works by iterating through both input lists simultaneously, comparing the first elements of each list at every step, and selecting the smaller (or larger, depending on the desired sorting order) of the two elements to be added to the resulting merged list. Once an element is chosen, it is removed from the original list, and the process is repeated until one of the lists is empty. At this point, the remaining elements in the non-empty list are simply appended to the merged list, as they are already sorted. The time complexity of the Merge Two Sorted Lists Algorithm is O(n), where n is the total number of elements in both input lists, making it an efficient approach to combining sorted data.
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        ListNode prev_head(0);
        ListNode *sorted_list = &prev_head;
        
        while (l1 && l2) {
            if (l1->val < l2->val) {
                sorted_list->next = l1;
                l1 = l1->next;
                sorted_list = sorted_list->next;
            }
            else {
                sorted_list->next = l2;
                l2 = l2->next;
                sorted_list = sorted_list->next;
            }
        }
        
        while (l1) {
            sorted_list->next = l1;
            l1 = l1->next;
            sorted_list = sorted_list->next;
        }
        while (l2) {
            sorted_list->next = l2;
            l2 = l2->next;
            sorted_list = sorted_list->next;
        }
        return prev_head.next;
    }
};

LANGUAGE:

DARK MODE: