2013-03-08 上机实验题
1.构建两个顺序表示的非空线性表LA和LB (数据元素为整型,其值自行确定);
2.从线性表LA中删除第i 个元素;
3.将元素e插入到线性表LB中的第i个元素之后;
4.假设LA中不含重复的元素 (LB同),将线性表LA和LB合并,并输出结果,要求结
果中不含重复的元素。
//构建两个顺序表(定义、初始化)
//在一个顺序表中删除指定位置的元素
//在一个顺序表中指定位置插入一个新元素
//将两个线性表LA和LB进行合并
//遍历LB, 如果其中的数据元素不在LA中,则将其插入LA,否则不予处理
//打印线性表LA
#define List_Init_Size 100
#define LISTINCREMENT 10
typedef int Status;
typedef struct {
int * elem;
int length; // 当前长度
int ListSize; // 当前分配的存储容量
}SqList;
Status Initialize_table (SqList &L) {// 初始化线性表
int i, m, data;
L.elem=(int *)malloc(List_Init_Size *sizeof(int));
if (!L.elem) { // 为线性表分配空间
printf("Overflow");
return FAILURE; }
L.ListSize=List_Init_Size; L.length=0;
printf ("Please input the size of linear table (<=%d): "+ List_Init_Size);
scanf_s("%d",&m);
for (i=0;i<m;i++) { // 依次输入线性表的数据元素
printf("Please input the NO.%d element : ", i+1);
scanf_s("%d",&data);
*(L.elem+i)=data;
L.length++;
}
return SUCCESS;
}
Status ListDelete (SqList &L, int i, int &e) {
// 从线性表中删除第i个元素,用e返回
int *p, *q;
if ((i<1) || (i>L.length)) //检查i值是否合法
return -1;
p=L.elem+i-1; // 找到删除位置
e=*p;
q=L.elem+L.length-1; //找到最后一个元素位置
for (++p; p<=q; ++p) //数据元素前移
*(p-1)=*p;
--L.length; //修改表长
return SUCCESS;
}
Status ListInsert(SqList &L, int i, int e) {
// 在线性表中第i个位置后插入元素e
int *p,*q;
if (i<0 || i>L.length) return FAILURE;
if (L.length >= L.ListSize){
p=(int*)realloc(L.elem,(L.ListSize+ListIncrement)*sizeof(int));
if (p==NULL) return FAILURE;
L.elem=p;L.ListSize+=ListIncrement;
}
q=L.elem+i; //即在第i+1个位置上插入元素e
for (p=L.elem+L.length-1;p>=q;--p)
*(p+1)=*p;
*q=e;
++L.length; // 修改表长
return SUCCESS;
}
Status MergeList (SqList &L1,SqList L2) {
// 合并线性表L1和L2
int i=0,k=L1.length;
int ai;
while (i < L2.length) { // 将第2个线性表中的元素
// 根据合并规则加入到第1个线性表中
ai = *(L2.elem + i);
if (!ExistsIn(L1, ai))
ListInsert(L1, k++, ai);
++i;
}
return OK;
}// end of function
Status PrintSq (SqList L) {
// 打印线性表的所有数据元素
int i;
printf("Allocated Memory Size=%d Length=%d ", L.ListSize, L.length);
for (i=0;i<L.length;i++)
printf("%d",L.elem[i]);
printf ("\n");
return OK;
}
Status main (void) {
int result;
SqList La, Lb;
Initialize_table (La); // 初始化线性表Initialize_table (Lb);
ListDelete (La, 3, result); // 删除元素
ListInsert (Lb, 4, 35); // 插入元素
MergeList (La, Lb); //合并线性表
PrintSq (La); // 打印线性表free (La.elem); // 释放存储空间free (Lb.elem);
return SUCCESS;
}。