//两个增序链表的合并,有序链表带空白头结点
#include<iostream>
using namespace std;
struct node{
int data;
node * next;
}; //这个分号不能少
node * createList(){
node * head, * rear;
head=new node;//或者head=(node)malloc(sizeof(struct node)); 新建空白节点
rear=head;
int data;cin>>data;
while(data != -1){
node * tmp=new node;
tmp->data=data;
rear->next=tmp;
rear=tmp;
cin>>data;
}
rear->next=NULL;
return head;
}
node * mergeList(node * a,node *b){
node *ha,* hb,* hc_head,* hc_rear;
ha=a->next;
hb=b->next;
hc_head=new node;
hc_rear=hc_head;
while(ha && hb){
node * tmp=new node;
if(ha->data <= hb->data){
tmp->data=ha->data;
hc_rear->next=tmp;
hc_rear=tmp;
ha=ha->next;
}else{
tmp->data=hb->data;
hc_rear->next=tmp;
hc_rear=tmp;
hb=hb->next;
}
}
while(ha){
node *tmp=new node;
tmp->data=ha->data;
hc_rear->next=tmp;
hc_rear=tmp;
ha=ha->next;
}
while(hb){
node *tmp=new node;
tmp->data=hb->data;
hc_rear->next=tmp;
hc_rear=tmp;
hb=hb->next;
}
hc_rear=NULL;
return hc_head;
}
void * coutList(node * l){
l=l->next;
int flag=0;
while(l){
if(flag==0) flag=1;
else cout<<" ";
cout<<l->data;
l=l->next;
}
}
int main(){
node * a,* b,* c;
a=createList();
b=createList();
c=mergeList(a,b);
coutList(c); cout<<endl;
return 0;
}
/*输入样例:
1 3 5 -1
2 4 6 8 10 -1
输出样例:
1 2 3 4 5 6 8 10*/
两个有序链表合并成一个有序链表
最新推荐文章于 2024-05-01 16:00:54 发布