將兩個(gè)有序的鏈表通過(guò)歸并的形式合并為一個(gè)有序的鏈表
#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;
}
作者原創(chuàng)悦即,如需轉(zhuǎn)載及其他問(wèn)題請(qǐng)郵箱聯(lián)系:lwqiang_chn@163.com。
個(gè)人網(wǎng)站:https://www.myqiang.top。