Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
// recursive solution, time O(m+n), much more space complexity
/**
* 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;
if(l1->val <= l2->val)
{
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
else
{
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
my 非递归法
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode* p = l1;
ListNode* q = l2;
ListNode* x = (l1->val <= l2->val) ? l1 :l2;
ListNode* c;
while(p&&q)
{
if(p->val <=q->val)
{
c->next = p;
c = c->next;
p = p->next;
}
else
{
c->next = q;
c = c->next;
q = q->next;
}
}
if(!p)
{
c->next = q;
}
if(!q)
{
c->next = p;
}
return x;
}
};
// merge sort, adding while comparing, time O(m+n)
class Solution_MergeSort {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode dummy(0); //头!
ListNode *curr = &dummy;
while (l1 && l2)
{
if (l1->val < l2->val)
{
curr->next = l1;
curr = l1;
l1 = l1->next;
}
else
{
curr->next = l2;
curr = l2;
l2 = l2->next;
}
}
if (!l1)
{
curr->next = l2;
}
if (!l2)
{
curr->next = l1;
}
return dummy.next;
}
};