且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

合并两个排好序的单链表

更新时间:2022-08-12 19:06:25

示例

合并两个排好序的单链表

思路一:两个链表同时逐个遍历

参考代码

合并两个排好序的单链表
ListNode* combinList(ListNode *head_1, ListNode *head_2)
{
    ListNode *head_3 = NULL;
    if(head_1 == NULL)
    {
        head_3 = head_2;
    }
    else if(head_2 == NULL)
    {
        head_3 = head_2;
    }
    else
    {
        ListNode *p1 = head_1;
        ListNode *p2 = head_2;
        ListNode *pre = NULL;
        if(p1->value < p2->value)
        {
            head_3 = p1;
            pre = head_3;
            p1 = p1->next;
        }
        else
        {
            head_3 = p2;
            pre = head_3;
            p2 = p2->next;
        }
        while(p1 && p2)
        {
            if(p1->value < p2->value)
            {
                pre->next = p1;
                pre = p1;
                p1 = p1->next;
            }
            else
            {
                pre->next = p2;
                pre = p2;
                p2 = p2->next;
            }
        }
        if(p1)
            pre->next = p1;
        if(p2)
            pre->next = p2;
    }
    return head_3;
}
合并两个排好序的单链表

思路二:递归

参考代码

合并两个排好序的单链表
ListNode* combinListRecursion(ListNode *head_1, ListNode *head_2)
{
    if(head_1 == NULL)
        return head_2;
    else if(head_2 == NULL)
        return head_1;
    ListNode *head = NULL;
    if(head_1->value < head_2->value)
    {
        head = head_1;
        head->next = combinListRecursion(head_1->next, head_2);
    }
    else
    {
        head = head_2;
        head->next = combinListRecursion(head_1, head_2->next);
    }
    return head;
}
合并两个排好序的单链表

执行

 

合并两个排好序的单链表 View Code

 

 




本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/3609025.html,如需转载请自行联系原作者