This is my solution


  • 0
    L
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
            if (l1 == NULL) return l2;
            if (l2 == NULL) return l1;
            
            ListNode *small, *big, *next, *head;
            
            if (l1->val < l2->val) { small = l1; big = l2; }
            else { small = l2; big = l1; }
            head = small;
            
            while (small != NULL && big != NULL) {
                if (small->next == NULL || small->next->val > big->val) {
                    next = small->next;
                    small->next = big;
                    small = big;
                    big = next;
                } else {
                    small = small->next;
                }
            }
            
            return head;
        }

  • 0
    S
    This post is deleted!

  • 0
    S
    This post is deleted!

  • 0
    J

    Although program is a little bit obscure, it is refined when carefully looking.


  • 0
    T

    Refined code:

    class Solution {
    public:
        ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
            ListNode *aux = new ListNode(0);
            ListNode *tmp = aux;
    
            while(l2) {      
                if (l1 == NULL) {
                    l1 = l2;
                    break;
                }
                else if(l1->val < l2->val) {
                    tmp = tmp->next = l1;
                    l1 = l1->next;
                }
                else {
                    tmp = tmp->next= l2;
                    l2 = l2->next;
                }
            }
    
            tmp->next = l1;
            tmp = aux->next;
            delete aux;
    
            return tmp;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.