菜鸟刷力扣 7

合并两个有序链表

在这里插入图片描述思路: 判断是否有空链表
if (list1 == nullptr) return list2;
if (list2 == nullptr) return list1;

     如果没有空链表
     1.先比较 2个链表头元素的大小,确定新链表的起始地址,确定后将地址后移(因为当前元素已经进入新链表了,没有再比一次的必要)
     2.比较后面2个元素的大小,将小的元素地址加入链表中。之后地址后移
     3.当有一个地址为空时,新地址的的后面直接拼接上最后的。

代码如下:

class Solution {
public:

    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        ListNode* temp = nullptr;
        ListNode* r_temp = nullptr;
        if (list1 == nullptr) return list2;
        if (list2 == nullptr) return list1;
        if (list1->val > list2->val)
        {
            temp = list2;
           r_temp = list2;
            list2 = list2->next;
        }
        else
        {
            temp = list1;
            r_temp = list1;
            list1 = list1->next;
        }
        while (list1 != nullptr && list2 != nullptr)
        {
            temp->next = (list1->val < list2->val ? list1 : list2);
            if (temp->next == list1)
            {
                temp = list1;
                list1 = list1->next;

            }
            else {
                temp = list2;
                list2 = list2->next;
            }
        }
        if (list1 == nullptr)
        {
            temp->next = list2;
        }
        else {
            temp->next = list1;
        }
        return r_temp;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值