题目描述
题目分析
首先我看到了排序的问题,先想到的是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;
}
}
};