LeetCode-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.

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        ListNode* root;
        ListNode* tail;
        if(l1!=NULL&&l2!=NULL){
            if(l1->val>l2->val){
                root=l2;
                tail=root;
                l2=l2->next;
            }
            else{
                root=l1;
                tail=root;
                l1=l1->next;
            }
            while(l1!=NULL&&l2!=NULL){
                if(l1->val>l2->val){
                    tail->next=l2;
                    tail=tail->next;
                    l2=l2->next;
                }
                else{
                    tail->next=l1;
                    tail=tail->next;
                    l1=l1->next;
                }
            }
            if(l1!=NULL)tail->next=l1;
            if(l2!=NULL)tail->next=l2;
            return root;
        }
        else{
            if(l2==NULL)return l1;
            else return l2;
        }
    }
};

 

posted @ 2013-09-15 14:30  懒猫欣  阅读(142)  评论(0编辑  收藏  举报