Merge Two Sorted Lists

来源:互联网 发布:儿童计算机编程 编辑:程序博客网 时间:2024/05/29 08:17
/**
 * 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)
        return l2;
        if(l2==NULL)
        return l1;
        
        ListNode *p=l1;
        ListNode *q=l2;
        ListNode *head=NULL;
        ListNode *lcode=NULL;
        
        while(p&&q)
        {
            if(head==NULL)
            {
                if(p->val<q->val)
                {
                    head=lcode=p;
                    p=p->next;
                    lcode->next=NULL;
                }
                else
                {
                    head=lcode=q;
                    q=q->next;
                    lcode->next=NULL;
                }
            }
            else
            {
                if(p->val<q->val)
                {
                    lcode->next=p;
                    lcode=p;
                    p=p->next;
                    lcode->next=NULL;
                    //p=p->next;
                    
                }
                else
                {
                    lcode->next=q;
                    lcode=q;
                    q=q->next;               //
                    lcode->next=NULL; //这两行的顺序不能更换
                    
                }
            }
        }
        
        if(p)
        {lcode->next=p;
        //p=p->next;
        }
        else if(q)
        {
        lcode->next=q;
        //q=q->next;
        }
        return head;
    }
};
0 0
原创粉丝点击