将两个有序的链表通过归并的形式合并为一个有序的链表
#include<iostream>
using namespace std;
class node{
public:
int value;
node* next;
node(){}
node(int value){
this->value=value;
this->next=NULL;
}
node(int value, node* next){
this->value=value;
this->next=next;
}
};
int main(){
node* list1=new node(1);
list1->next=new node(3, new node(5)); // 1,3,5
node* list2=new node(0, new node(4, new node(8))); // 0,4,8
node* result=new node();
node *p3=result, *p1=list1, *p2=list2;
for(; p1!=NULL && p2!=NULL; )
if(p1->value<p2->value){
p3->next=p1;
p3=p3->next;
p1=p1->next;
}else{
p3->next=p2;
p3=p3->next;
p2=p2->next;
}
for(; p1!=NULL; ){
p3->next=p1;
p3=p3->next;
p1=p1->next;
}
for(; p2!=NULL; ){
p3->next=p2;
p3=p3->next;
p2=p2->next;
}
result=result->next;
while(result!=NULL){
cout<<result->value<<"\t";
result=result->next;
}
return 0;
}
作者原创,如需转载及其他问题请邮箱联系:lwqiang_chn@163.com。
个人网站:https://www.myqiang.top。
网友评论