#include<stdio.h>
#include<stdlib.h>
typedef struct s{
int data;
struct s *next;
}node,*snode;
node *creatlist(void);
node *merge(node *a,node *b);
void print(node *head);
int main(){
snode L1,L2;
L1=creatlist();
print(L1);
L2=creatlist();
print(L2);
print(merge(L1,L2));
}
node *creatlist(void){
node *head=NULL;
node *p=NULL;
node *r=NULL;
int x;
scanf("%d",&x);
while(x!=-1){
p=(node *)malloc(sizeof(struct s));
p->data=x;
p->next=NULL;
if(head==NULL){
head=p;
r=p;
}else{
r->next=p;
r=p;
}
scanf("%d",&x);
}
return head;
}
//合并仅仅是断开链,然后重新结合成新的链表,那么就要寻找head的位置;
//交集要有第三个链表
node *merge(node *a,node *b) {
node *ha,*hb;
node *head=NULL;
node *r=NULL;
ha=a;
hb=b;
if(a!=NULL&&b==NULL){
head=ha;
}else if(a==NULL&&b!=NULL){
head=hb;
}else if(a!=NULL&&b!=NULL){
if(a->data<b->data){
head=ha;
r=a;
a=a->next;
}else{
head=hb;
r=b;
b=b->next;
}
}
while(1){
if(a->data<b->data){
r->next=a;
r=a;
a=a->next;
if(a==NULL){
r->next=b;
break;
}
}else{
r->next=b;
r=b;
b=b->next;
if(b==NULL){
r->next=a;
break;
}
}
}
return head;
}
void print(node *head){ //打印一个列表
node *p;
p=head;
while(p){
printf("%d->",p->data);
p=p->next;
}
if(p==NULL)
printf("NULL");
printf("\n");
}
寻找两个有序链表的并集
最新推荐文章于 2021-03-13 22:39:05 发布