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.

class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        ListNode head(0),*p = &head;
        while(l1 && l2){
            if (l1->val < l2->val){
                p = p->next = l1;
                l1 = l1->next;
            }else{
                p = p->next = l2;
                l2 = l2->next;
            }
        }
        if (l1){
            p->next = l1;
        }else if (l2){
            p->next = l2;
        }else{
            p->next = NULL;
        }
        return head.next;
    }
};

 

posted @ 2013-07-12 06:26  一只会思考的猪  阅读(103)  评论(0编辑  收藏  举报