25:合并两个排序的链表

非递归解法:

ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        ListNode*root=new ListNode(-1);
        ListNode*head=root;
        while(pHead1&&pHead2)
        {
            if(pHead1->valval)head->next=pHead1,head=head->next,pHead1=pHead1->next;
            else head->next=pHead2,head=head->next,pHead2=pHead2->next;
        }
        if(pHead1)head->next=pHead1;
        if(pHead2)head->next=pHead2;
        return root->next;
    }

递归解法:

ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        if(!pHead1)return pHead2;
        if(!pHead2)return pHead1;
        ListNode* head=NULL;
        if(pHead1->valval)
        {
            head=pHead1;
            head->next=Merge(pHead1->next,pHead2);
        }
        else head=pHead2,head->next=Merge(pHead1,pHead2->next);
        return head;
    }

你可能感兴趣的:(25:合并两个排序的链表)