【leetcode】21.合并两个有序链表

题目描述

在这里插入图片描述

题目分析

首先我看到了排序的问题,先想到的是sort函数,于是把两个链表的值重新分配给一个新链表
但是更快的方法应该是将两个链表挨个进行比较,对链表的next进行重新分配
这样的时间复杂度应该是O(N+M),而sort的时间复杂度是O(logn),所以从速度来说应该挨个比较

看了题解还有使用递归解题的,太强了。

题解代码

全部排序重新分配链表代码(略麻烦)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        
    if(l1==NULL)
        return l2;
    if(l2==NULL)
        return l1;
        
    vector <int> vec;
    while(l1!=NULL)
    {
        vec.push_back(l1->val);
        l1 = l1->next;
    }
    while(l2!=NULL)
    {
        vec.push_back(l2->val);
        l2 = l2->next;
    }
    sort(vec.begin(),vec.end());

    ListNode *ans = new ListNode(vec[0]);
    ListNode *head = ans;
    for(int i=1;i<vec.size();i++)
    {
        head->next = new ListNode(vec[i]);
        head = head->next;
    }
        return ans;
    }
};

简单粗暴的挨个比较

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        
    ListNode *ans = new ListNode(1);
    ListNode *head = ans ;
        
     while(l1!=NULL&&l2!=NULL)
    {
        if(l1->val<l2->val)
        {
            head->next=l1;
            l1 = l1->next;
        }
        else
        {
            head->next = l2;
            l2 = l2->next;
        }
        head = head->next;
    }
    head->next = l1?l1:l2;
    return ans->next;
    }
};

递归解题(转载)

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(l1 == NULL) return l2;
        else if (l2 == NULL) return l1;
        else if (l1->val < l2->val) {
            l1->next = mergeTwoLists(l1->next, l2);
            return l1;
        } else {
            l2->next = mergeTwoLists(l1, l2->next);
            return l2;
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值