剑指offer---合并两个排序的链表

题目17:合并两个排序的链表(leetcode链接:https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/

题目分析

方法1

方法2

比较两个链表的头结点,较小的一个节点就是新链表的头结点。剩下的节点和另一个链表还可以以同样的方式进行判断找出较小的一个节点,这就是一个递归的过程。

代码描述

方法1

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(l1 == NULL && l2 == NULL)
            return NULL;
        if(l1 == NULL || l2 == NULL)
            return l1 == NULL ? l2:l1;

        //两个链表都不为空,创建新的链表节点遍历链表
        ListNode* newhead = (ListNode*)malloc(sizeof(ListNode));
        ListNode* tail = newhead;
        while(l1 && l2)
        {
            if(l1->val < l2->val)
            {
                tail->next = l1;
                l1 = l1->next;
            }
            else
            {
                tail->next = l2;
                l2 = l2->next;
            }
            tail = tail->next;
        }
        //将没有链接完的链表拼接在新链表的表尾
        if(l1)
        {
            tail->next = l1;
        }
        else
        {
            tail->next = l2;
        }
        ListNode* ret = newhead->next;
        free(newhead);
        newhead = NULL;
        return ret;
    }
};

方法2

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(l1 == NULL)
            return l2;
        else if(l2 == NULL)
            return l1;
        
        //创建一个头结点
        ListNode* head = NULL;
        if(l1->val < l2->val)
        {
            head = l1;
            head->next = mergeTwoLists(l1->next,l2);
        }
        else
        {
            head = l2;
            head->next = mergeTwoLists(l1,l2->next);
        }
        return head;
    }
};

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

疯狂嘚程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值