两个顺序表求交集,运行时没结果,算法有问题?
[qq][*]876563255
//C要求元素各不同且要用A表空间存放C,元素递增有序
#include<stdio.h>
#include<stdlib.h>
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define OVERFLOW 0
#define OK 1
typedef struct
{
int * elem;
int length;
int listsize; //当前分配的存储容量(以sizeof(int)为单位
}SqList;
int InitList_Sq(SqList &L) //构造一个空的线性表
{
L.elem = (int *) malloc (LIST_INIT_SIZE * sizeof (int));
if (! L.elem)
exit(OVERFLOW);
L.length = 0;
L.listsize = LIST_INIT_SIZE;
return OK;
} //InitList_Sq
int SqList_Intersect_True(SqList &A, SqList B) //求元素递增排列的线性表A和B的元素的交集并存回A中
{
int i = 0;
int j = 0;
int k = 0;
int alength = 0;
while (A.elem[i]&&B.elem[j])
{
if (A.elem[i]<B.elem[j])
{
i++;
}
else if (A.elem[i]>B.elem[j])
{
j++;
}
else if (A.elem[i] != A.elem[k]) //
{
A.elem[k] = A.elem[i]; //当发现了一个在A,B中都存在的元素
i++; //且C中没有,就添加到C中
j++;
k++;
alength++;
}
} //while
while (A.elem[k])
{
A.elem[k++]=0;
}
return alength;
} //SqList_Intersect_True
int main()
{
int m;
int n;
int i;
SqList A;
SqList B;
int k = 0;
int alength;
InitList_Sq(A); //构造顺序线性表A
printf("构造顺序线性表A:\n");
printf("输入元素的个数m:");
scanf("%d",&m);
printf("输入递增有序的(允许有相同的)%d个整型数据元素:\n",m);
for (i = 0; i<m; i++)
{
scanf("%d",&A.elem[i]);
}
InitList_Sq(B); //构造顺序线性表B
printf("构造顺序线性表B:\n");
printf("输入元素的个数n:");
scanf("%d",&n);
printf("输入递增有序的(允许有相同的)%d个整型数据元素:\n",n);
for (i = 0; i<n; i++)
{
scanf("%d",&B.elem[i]);
}
alength = SqList_Intersect_True(A, B); //求元素的交集,这种调用,有参数返回!
printf("求交后的顺序表C:\n");
for (k = 0; k<alength; k++) //输出
{
printf("%d ",A.elem[k]);
}
printf("\n");
free(A.elem);
free(B.elem);
return 0;
}
[[it] 本帖最后由 zwqbq 于 2008-10-5 13:09 编辑 [/it]]