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.
比较两个链表的第一个元素,将较小的元素放入新的链表中,向后移动该较小的链表头指针.算法时间复杂度为O(l1.size()+l2.size()).
#include<iostream>
using namespace std;
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;
ListNode* t1=l1, *t2=l2;
ListNode* result=new ListNode(0);
ListNode* l=result;
while (t1!=NULL||t2!=NULL) {
if (t2==NULL||(t1!=NULL && t1->val <= t2->val)) {
l->val=t1->val;
t1=t1->next;
} else {
l->val=t2->val;
t2=t2->next;
}
if (t1!=NULL||t2!=NULL) {
l->next=new ListNode(0);
l=l->next;
}
}
return result;
}
};
int main() {
Solution s;
ListNode* l1=new ListNode(1);
l1->next=new ListNode(5);
ListNode* l2=new ListNode(2);
l2->next=new ListNode(3);
ListNode* l=s.mergeTwoLists(l1,l2);
while(l) {
cout << l->val << " ";
l=l->next;
}
}