LeetCode 21. Merge Two Sorted Lists

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.


I personally prefer to add a dummy node. But need to remember to delete it after. This will cause memory overflow in some cases.

  ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(!l1) return l2;
        if(!l2) return l1;
        ListNode* dummy = new ListNode(0);
        ListNode* newHead = dummy;
        ListNode* l1_node = l1;
        ListNode* l2_node = l2;
        while(l1_node && l2_node) {
            if(l1_node->val <= l2_node->val) {
                ListNode* l1_next = l1_node->next;
                dummy->next = l1_node;
                dummy = l1_node;
                l1_node = l1_next;
            } else {
                ListNode* l2_next = l2_node->next;
                dummy->next = l2_node;
                dummy = l2_node;
                l2_node = l2_next;
            }
        }
        if(l1_node) dummy->next = l1_node;
        if(l2_node) dummy->next = l2_node;
        ListNode* head = newHead->next;
        delete newHead;
        return head;
    }


你可能感兴趣的:(LeetCode 21. Merge Two Sorted Lists)