顺序表合并问题
将顺序表LA 和LB 合并成顺序表LC:
#include
#include
#include
#define LIST_INIT_SIZE 80
#define LISTINCREMENT 10
typedef struct{
int *elem;
int length;
int listsize;
}SqList;
SqList Init(SqList L); //初始化函数
SqList Input(SqList L); //输入LA 和 LB 顺序表数据
void Output(SqList L); //输出函数
SqList Merge(SqList LA,SqList LB,SqList LC);
SqList RenewLC(SqList LC); //此函数为分配LC顺序表增量
int main(void)
{
SqList LA,LB,LC;
LA=Init(LA);
LB=Init(LB);
LA=Input(LA);
LB=Input(LB);
Output(LA);
Output(LB);
LC=Merge(LA,LB,LC);
Output(LC);
getch();
return 0;
}
SqList Init(SqList L)
{
L.elem=(int *)malloc(LIST_INIT_SIZE * sizeof(int));
if(!L.elem)
{
printf("Dynamic memory malloc failure.\n");
exit(1);
}
L.length=0;
L.listsize=LIST_INIT_SIZE;
return L;
}
SqList Input(SqList L)
{
int value;
int *newbase;
printf("Please input value: ");
scanf("%d",&value);
while(value)
{
L.elem[L.length]=value;
L.length++;
if(L.length>=L.listsize)
{
newbase=(int *)realloc(L.elem,(L.listsize+LISTINCREMENT) * sizeof(int));
if(!newbase)
{
printf("Renew malloc memory failure.\n");
exit(1);
}
L.elem=newbase;
L.listsize+=LISTINCREMENT;
}
scanf("%d",&value);
}
return L;
}
void Output(SqList L)
{
int i;
for(i=0;i<=L.length-1;i++)
printf("%d\t",L.elem[i]);
free(L.elem);
printf("\n");
}
SqList Merge(SqList LA,SqList LB,SqList LC) //主要就是此函数
{
int i,j;
LC=Init(LC);
i=0;
j=0;
while(i<=LA.length-1 && j<=LB.length-1)
{
if(LA.elem[i]<=LB.elem[j])
{
LC.elem[LC.length]=LA.elem[i];
LC.length++;
i++;
if(LC.length>=LC.listsize)
LC=RenewLC(LC);
}
else
{
LC.elem[LC.length]=LB.elem[j];
LC.length++;
j++;
if(LC.length>=LC.listsize)
LC=RenewLC(LC);
}
}//while
while(i<=LA.length-1)
{
LC.elem[LC.length]=LA.elem[i];
LC.length++;
i++;
if(LC.length>=LC.listsize)
LC=RenewLC(LC);
}
while(j<=LB.length-1)
{
LC.elem[LC.length]=LB.elem[j];
LC.length++;
j++;
if(LC.length>=LC.listsize)
LC=RenewLC(LC);
}
return LC;
}
SqList Renew(SqList LC)
{
int *newbase;
newbase=(int *)realloc(LC.elem,(LC.listsize+LISTINCREMENT) * sizeof(int));
if(!newbase)
{
printf("Renew malloc memory failure.\n");
exit(1);
}
LC.elem=newbase;
LC.listsize+=LISTINCREMENT;
return LC;
}
thank you!