Simple C++


  • 0
    J
    /**
     * 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) {
            if (l1 == NULL && l2 == NULL) {
                return NULL;
            }
            if (l1 == NULL) {
                return l2;
            }
            if (l2 == NULL) {
                return l1;
            }
            
            ListNode *l = NULL;
            ListNode *head = NULL;
            
            if (l1->val < l2->val) {
                l = head = l1;
                l1 = l1->next;
            }
            else {
                l = head = l2;
                l2 = l2->next;
            }
            
            while(true) {
                if (l1 == NULL) {
                    l->next = l2;
                    break;
                }
                if (l2 == NULL) {
                    l->next = l1;
                    break;
                }
                
                if (l1->val < l2->val) {
                    l->next = l1;
                    l = l1;
                    l1 = l1->next;
                }
                else {
                    l->next = l2;
                    l = l2;
                    l2 = l2->next;
                }
            }
            return head;
            
        }
    };
    

Log in to reply
 

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