#include<stdio.h>
#include<malloc.h>
#define MaxSize 50
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int length;
}Linknode;
int ListLength(Linknode&L)
{
return L.length;
}
int GetElem(Linknode L,int p,int&e)
{
if(p<1||p>L.length)
return 0;
e=L.data[p];
return 1;
}
int ListInsert(Linknode &L,int p,int e)
{
int i;
if(p<1||p>L.length||L.length==MaxSize-1)
return 0;
for(i=L.length;i>=p;--i)
L.data[i+1]=L.data[i];
L.data[p]=e;
return 1;
}
bool ListDelete(Linknode &L,int i,ElemType &e)
{
int j;
if(i<1||i>L.length)
return false;
i--;
e=L.data[i];
for(j=i;j<=L.length-1;j++)
L.data[j]=L.data[j+1];
L.length--;
return true;
}
void InitList(Linknode &L)
{
L.length=0;
}
void unionList(Linknode LA,Linknode LB,Linknode &LC)
{
int lena,lenb;
int Ae,Be,m,n,e;
int i=1,j=1,k=0;
InitList(LC);
lena=ListLength(LA);
lenb=ListLength(LB);
LC.length=lena+lenb;
while((i<=lena)&&(j<=lenb)){
GetElem(LA,i,Ae);
GetElem(LB,j,Be);
if(Ae<=Be){
ListInsert(LC,++k,Ae);
++i;
}else{
ListInsert(LC,++k,Be);
++j;
}
}
while (i<=lena){
GetElem(LA,i++,Ae);
ListInsert(LC,++k,Ae);
}
while(j<=lenb){
GetElem(LB,j++,Be);
ListInsert(LC,++k,Be);
}
for(n=1;n<=LC.length-1;n++){
if(LC.data[n]==LC.data[n+1])
{
m=n+1;
ListDelete(LC,m,e);
n--;
}
}
}
int main()
{
Linknode LA,LB,LC;
printf("请输入一个整数,表示LA中数据的个数:");
InitList(LA);
InitList(LB);
while(scanf("%d",&LA.length)!=EOF)
{
for(int i=1;i<=LA.length;i++)
{
scanf("%d",&LA.data[i]);
}
printf(" 请输入一个整数,表示LB线性表中数据的个数 : ");
scanf("%d",&LB.length);
for(int i=1;i<=LB.length;i++)
{
scanf("%d",&LB.data[i]);
}
printf(" 合并后的LC为 : ");
unionList(LA,LB,LC);
if(LC.length!=0)
{
printf("%d",LC.data[1]);
for(int i=2;i<=LC.length;i++)
printf(" %d",LC.data[i]);
}
printf("\n");
}
return 0;
}
数据结构——链表合并
最新推荐文章于 2024-07-06 19:08:33 发布