当前位置: 代码迷 >> C语言 >> 顺序表合并问题
  详细解决方案

顺序表合并问题

热度:435   发布时间:2006-03-16 23:53:00.0

[CODE]
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#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);
void Output(SqList L);
SqList Merge(SqList LA,SqList LB,SqList LC);
SqList RenewLC(SqList LC);

int main(void)
{
SqList LA,LB,LC;

LA=Init(LA);
LB=Init(LB);
LC=Init(LC);

LA=Input(LA);
LB=Input(LB);

Output(LA);
Output(LB);

LC=Merge(LA,LB,LC);

Output(LC);
free(LA.elem);
free(LB.elem);
free(LC.elem);

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:\n ");
scanf("%d",&value);

while(value)
{
L.elem[L.length++]=value;
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]);

printf("\n");
}

SqList Merge(SqList LA,SqList LB,SqList LC)
{
int i,j;

i=0;
j=0;

printf("%d\n", LA.elem[i]);
while(i<=LA.length-1 && j<=LB.length-1)
{
if(LA.elem[i]<=LB.elem[j])
{
LC.elem[LC.length++]=LA.elem[i++];
if(LC.length>=LC.listsize)
LC=RenewLC(LC);
}
else
{
LC.elem[LC.length++]=LB.elem[j++];
if(LC.length>=LC.listsize)
LC=RenewLC(LC);
}
}

while(i<=LA.length-1)
{
LC.elem[LC.length++]=LA.elem[i++];
if(LC.length>=LC.listsize)
LC=RenewLC(LC);
}

while(j<=LB.length-1)
{
LC.elem[LC.length++]=LB.elem[j++];
if(LC.length>=LC.listsize)
LC=RenewLC(LC);
}

return LC;
}

SqList RenewLC(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;
}



[/CODE]


----------------解决方案--------------------------------------------------------
楼上 printf("%d\n", LA.elem[i]); 去掉,是加的测试语句
----------------解决方案--------------------------------------------------------
  相关解决方案