剑指offer----合并两个有序链表

来源:互联网 发布:appstore不能更新软件 编辑:程序博客网 时间:2024/05/22 02:21

题目:合并两个递增的有序链表。

注意:测试时一定要考虑全面,当两个链表有一个或两个都为空的情况。

非递归:

 ListNode* Merge(ListNode* pHead1, ListNode* pHead2)    {        if(pHead1==NULL)            return pHead2;        if(pHead2==NULL)            return pHead1;        ListNode* head=NULL;        ListNode* cur=NULL;        if(pHead1->val < pHead2->val)        {                        cur=pHead1;            head=cur;            pHead1=pHead1->next;        }        else        {        cur=pHead2;            head=cur;            pHead2=pHead2->next;        }                while(pHead1!=NULL&&pHead2!=NULL)        {        if(pHead1->val < pHead2->val)            {             cur->next=pHead1;                pHead1=pHead1->next;            }            else            {            cur->next=pHead2;                pHead2=pHead2->next;            }            cur=cur->next;                    }        if(pHead1!=NULL)        {            cur->next=pHead1;                    }        else        {        cur->next=pHead2;                        }        return head;    }

递归:

 ListNode* Merge(ListNode* pHead1, ListNode* pHead2)    {        if(pHead1==NULL)            return pHead2;        if(pHead2==NULL)            return pHead1;        if(pHead1->val < pHead2->val)        {                        pHead1->next=Merge(pHead1->next,pHead2);            return pHead1;                  }        else        {            pHead2->next=Merge(pHead1,pHead2->next);            return pHead2;                    }     }}


0 0
原创粉丝点击