您的位置:首页 > 其它

合并俩个已排序的链表

2017-11-26 09:07 183 查看
非递归

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
ListNode* root=new ListNode(0);
ListNode* pre=root;
ListNode* p=l1;
ListNode* q=l2;
while(p && q){
if(p->val < q->val){
pre->next=p;
p=p->next;
}else{
pre->next=q;
q=q->next;
}
pre=pre->next;
}
/*
while(p){
pre->next=p;
pre=pre->next;
p=p->next;
}
while(q){
pre->next=q;
pre=pre->next;
q=q->next;
}*/
pre->next= p!=NULL ? p:q;
return root->next;
}

代码: 递归

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: