21. Merge Two Sorted Lists

来源:互联网 发布:页游挂机软件 编辑:程序博客网 时间:2024/06/10 04:02

21. Merge Two Sorted Lists
Difficulty: Easy

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.

合并两个已排序的链表,返回合并后的新链表。

思路:
方法一
递归解法,类似于归并排序中的合并两个已排序数组的操作。
思路清晰,代码简洁,不易出错。

//递归解法(较简洁),类似于归并排序中的合并两个已排序数组的操作struct ListNode* mergeTwoLists(struct ListNode* l1,struct ListNode* l2)  {    struct ListNode* retlist=NULL;    if(l1==NULL)        return l2;    else if(l2==NULL)        return l1;    if(l1->val<l2->val)     {        retlist=l1;        retlist->next=mergeTwoLists(l1->next,l2);    }    else    {        retlist=l2;        retlist->next=mergeTwoLists(l1,l2->next);    }    return retlist;}

方法二
将链表1的结点插入到链表2中
代码冗杂,容易出错

//普通解法(较繁琐),将链表1的结点插入到链表2中struct ListNode* mergeTwoLists(struct ListNode* l1,struct ListNode* l2)  {    struct ListNode* head,* node1,* node2,* temp;    if(l1==NULL)        return l2;    else if(l2==NULL)        return l1;    //以l2为返回链表    if(l1->val<l2->val)   //若头结点在l1,l1移到l2作为头结点,node1从l1的下一结点开始    {        node1=l1->next;        l1->next=l2;        head=l1;    }    else    //若头结点在l2,node1从l1开始    {        node1=l1;        head=l2;    }    node2=head;    //node2从返回链表的头结点开始    while(node1!=NULL && node2->next != NULL)    {        if(node1->val < node2->next->val)        {            temp=node2->next;            node2->next=node1;            node1=node1->next;  //            node2=node2->next;            node2->next=temp;        }        else        {            node2=node2->next;        }           }    if(node1!= NULL)   //链表2已合并完,链表1还有未合并的    {        node2->next=node1;    }    return head;}

两种方法的算法复杂度应该是一样的,但是递归解法更容易理解。

0 0
原创粉丝点击