链表 21.合并两个有序链表

题目

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

输入:1->2->4, 1->3->4

输出:1->1->2->3->4->4

题目来源

 

思路

第一个思路就是以迭代的方式,逐一比较链表元素大小关系,改变指针的指向,最后整合成一条有序的链表,这个思路比较简单。另外一个思路需要理解理解,用递归的方式。在写代码前,先想一想递归的公式。

result = L1+mergeTwoLists(L1->next,L2)  L1->val  < L2->val

result = L2+mergeTwoLists(L1,L2->next)  其他(L1->val  >= L2->val)

当L1的元素小于L2的元素时,合并的新链表 = L1当前节点 + L1剩余链表与L2链表的合并。反之则是,合并的新链表 = L2当前节点 + L2剩余链表与L1链表的合并。

因为合并的过程存在重复的操作,所以才使用递归。

递归出口为

if(!L1)
{
     return L2;
}
if(!L2)
{
     return L1;
}

即当L1为空,则合并链表为L2,当L2为空,则合并链表为L1。

 

代码实现

/**

*迭代

*/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
    if(!l1)
    {
        return l2;
    }
    if(!l2)
    {
        return l1;
    }
    
    struct ListNode *head = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode *p = head;


    while( l1 != NULL && l2 != NULL )
    {
        if( l1->val < l2->val  )
        {
            p->next = l1;
            l1 = l1->next;
        }
        else
        {
            p->next = l2;
            l2 = l2->next;
        }
        p = p->next;
    }
    /*
    *接上已经有序的部分链表
    */
    if (l1)      p->next = l1;
    else if (l2) p->next = l2;

    return head->next;
}

/**

*递归

*/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
    if(!l1)
    {
        return l2;
    }
    if(!l2)
    {
        return l1;
    }
    
    if( l1->val < l2->val )
    {
        l1->next = mergeTwoLists(l1->next,l2);
        return l1;
    }
    else
    {
        l2->next = mergeTwoLists(l1,l2->next);
        return l2;
    }
}

 

posted @ 2020-08-05 17:02  Rego  阅读(103)  评论(0)    收藏  举报