21. Merge Two Sorted Lists

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值