8ms C++ clear ,Non-recursive


  • 5
    G
    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            ListNode *Head=new ListNode(0);
            ListNode *pre=Head;
            while(l1&&l2)
            {
                if(l1->val<l2->val)
                  {
                      pre->next=l1;
                      pre=l1;
                      l1=l1->next;
                  }else
                  {
                      pre->next=l2;
                      pre=l2;
                      l2=l2->next;
                  }
            }
            if(l1)
                pre->next=l1;
            if(l2)
                pre->next=l2;
            ListNode *Result=Head->next;
            delete Head;
            return Result;
        }
    };

  • 1
    W

    Using head node to help reducing excessive judgement. The code is much cleaner than that do not use the trick. And pretty faster than the recursive ones. Thank you~


Log in to reply
 

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