//4.将2个从小到大排列的链表,合并为一个新链表(任然有序排列),合并时去掉重复的,打印3个链表。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct Node
{
int Data;
struct Node *Next;
};
struct Node* Create()
{
struct Node *L;
L=(struct Node *)malloc(sizeof(struct Node));
L->Next=NULL;
return L;
} // 创建空链表,带头结点
void Insert_sort(struct Node *L,int x)
{
struct Node *p,*q;
p=L;
while(p->Next!=NULL&&x>p->Next->Data)
{
p=p->Next;
}
q=(struct Node *)malloc(sizeof(struct Node));
q->Data=x;
q->Next=p->Next;
p->Next=q;
}
void Print(struct Node *L){
struct Node *q;
q=L->Next;
while(q!=NULL){
printf("%d ",q->Data);
q=q->Next;
}
};
int main()
{
struct Node *L1,*L2,*L3;
L1=Create();
L2=Create();
L3=Create();
// L1=(struct Node*)malloc(sizeof(struct Node));
// L1->Next=NULL;
// L2=(struct Node*)malloc(sizeof(struct Node));
// L2->Next=NULL;
// L3=(struct Node*)malloc(sizeof(struct Node));
// L3->Next=NULL;
srand((int)time(NULL));
int i;
for(i=0;i<10;i++)
{
Insert_sort(L1,rand()%100);
Insert_sort(L2,rand()%100);
}
struct Node *a,*b;
a=L1->Next;
b=L2->Next;
while(a!=NULL&&b!=NULL)
{
if(a->Next!=NULL&&a->Data==a->Next->Data)
{
a=a->Next;
}
else if(b->Next!=NULL&&b->Data==b->Next->Data)
{
b=b->Next;
}
else
{
if(a->Data<b->Data)
{
Insert_sort(L3,a->Data);
a=a->Next;
}
else if(a->Data>b->Data)
{
Insert_sort(L3,b->Data);
b=b->Next;
}
else
{
Insert_sort(L3,b->Data);
b=b->Next;
a=a->Next;
}
}
}
if(a==NULL)
{
while(b!=NULL)
{
if(b->Next!=NULL&&b->Data==b->Next->Data)
{
b=b->Next;
}
Insert_sort(L3,b->Data);
b=b->Next;
}
}
else
{
while(a!=NULL)
{
if(a->Next!=NULL&&a->Data==a->Next->Data)
{
a=a->Next;
}
Insert_sort(L3,a->Data);
a=a->Next;
}
}
Print(L1);
printf("\n");
Print(L2);
printf("\n");
Print(L3);
return 0;
}
实验2.4合并两个链表,并有序排列且无重复元素
最新推荐文章于 2023-07-09 16:03:33 发布