Monday, November 25, 2013

LeetCode Problem : Merge Two Sorted Lists

Problem


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.

Code

ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    ListNode *result = 0;
    ListNode *head = 0;
    while(l1 || l2){
        ListNode *node;
        if(l1 && l2){
            if(l1->val < l2->val){
                node = l1;
                l1 = l1->next;
            }
            else{
                node = l2;
                l2 = l2->next;
            }
        }
        else if(l1){
            node = l1;
            l1 = l1->next;
        }
        else{
            node = l2;
            l2 = l2->next;
        }
        if(!head){
            head = node;
            result = head;
        }
        else{
            result->next = node;
            result = result->next;
        }
    }
    if(result)
    result->next = 0;
    return head;
}

No comments:

Post a Comment