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.
我这里有两个思路,代码都挺简洁的,一个是把其中一个链表中的数据全部插入到另一个链表中去;另一个是采用归并排序的思路,时间复杂度都是0(m+n)
下面分别给出两个思路的代码:
下面这个是采用将一个链表中的节点不断的插入到另一个链表中去
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
ListNode* temp=new ListNode(0);
temp->next=l1;
l1=temp;
ListNode*p,*q;
p=l1,q=l1->next;
ListNode*m=l2;
for(; l2 ;l2=m){
m=l2->next;
for( ; q && l2->val>q->val ; p=p->next,q=q->next);
l2->next=q;
p->next=l2;
p=p->next;
}
ListNode* ret=temp->next;
delete temp;
return ret;
}
};下面这个采用归并排序的思路
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *q1,*q2,*cur;
ListNode *head=new ListNode(-1);
head->next=NULL,cur=head;
for( ; l1 && l2 ; ){
if(l1->val<l2->val){
cur->next=l1;
l1=l1->next;
}else{
cur->next=l2;
l2=l2->next;
}
cur=cur->next;
}
cur->next= l1?l1:l2;
cur=head->next;
delete head;
return cur;
}
};
本文介绍两种合并两个有序链表的方法:一种通过不断插入节点,另一种采用类似归并排序的思路。这两种方法的时间复杂度均为O(m+n)。
210

被折叠的 条评论
为什么被折叠?



