LeetCode 21. Merge Two Sorted Lists

21. Merge Two Sorted Lists

Difficulty: easy

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

Only Version:

/**
 * 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) {
        ListNode* head = new ListNode(INT_MIN);
        auto itr = head;
        
        while (l1 != NULL || l2 != NULL) {
            if (l2 == NULL || (l1 != NULL && l1->val < l2->val)) {
                itr = itr->next = l1;
                l1 = l1->next;
            } else {
                itr = itr->next = l2;
                l2 = l2->next;
            }
        }
        
        return head->next;
    }
};

Rate:
Runtime: 4 ms, faster than 98.91% of C++ online submissions for Merge Two Sorted Lists.
Memory Usage: 8.9 MB, less than 81.15% of C++ online submissions for Merge Two Sorted Lists.

水过.