线性表的顺序实现

include

include

define MAX 10

typedef struct Sqlist{
int *data;
int length;
int lengthsize;
}Sqlist;
int print(Sqlist T){
Sqlist *q;
q = &T;
int i;
if(q->length == 0) return -1;
for(i = 0; i < q->length; i++){
printf("%d ", q->data[i]);
}
return 0;
}
Sqlist createSqlist(Sqlist *T){
int i;
T->data = (int *)malloc(MAX *sizeof(int));
printf("请输入顺序表长度:");
scanf("%d", &T->length);
T->lengthsize = MAX;
if(T->length > T->lengthsize) return T;
printf("\n请输入顺序表数字:\n");
for(i = 0; i < T->length; i++){
scanf("%d", &T->data[i]);
}
print(
T);
return *T;
}

int Find(Sqlist T, int x){
int i;
Sqlist *p;
p = &T;
for(i = 0; i < p->length; i++){
if(p->data[i] == x){
printf("find:%d, pos:%d", x, i+1);
return 0;
}
}
printf("nofind:%d", x);
return -1;
}

int insertSqlist(Sqlist *T, int pos, int x){
int *q, *p;
if(pos<1 || pos>T->length+1) return -1;
if(T->length >= T->lengthsize){
T->data = (int )realloc(T->data, (T->lengthsize+MAX)sizeof(int));
T->lengthsize += MAX;
}
q = &(T->data[pos-1]);
for(p = &(T->data[T->length-1]); p >= q; p--){
*(p+1) = *p;
}
q = x;
T->length++;
print(
T);
return 0;
}
int Dele(Sqlist *T){
int pos;
int *p, *q;
printf("\n请输入要删除的位置:");
scanf("%d", &pos);
p = &(T->data[pos-1]);
q = T->data+T->length-1;
if(pos < 1 || pos >T->length) return -1;
for(++p; p <= q; p++){
*(p-1) = p;
}
T->length--;
print(
T);
return 0;
}
void Mergelist(Sqlist *Ta, Sqlist *Tb, Sqlist *Tc){
int i=0, j=0, k=0;
Tc->lengthsize = Tc->length = Ta->length+Tb->length;
Tc->data = (int *)malloc(Tc->lengthsize *sizeof(int));
while(i <= Ta->length-1 && j <= Tb->length-1){
if(Ta->data[i] <= Tb->data[j]){
Tc->data[k] = Ta->data[i];
i++;
k++;
}else{
Tc->data[k] = Tb->data[j];
j++;
k++;
}
}
while(i <= Ta->length-1){
Tc->data[k] = Ta->data[i];
i++;
k++;
}
while(j <= Tb->length-1){
Tc->data[k] = Tb->data[j];
j++;
k++;
}
}

int main()
{
Sqlist Ta, Tb, Tc;
int x, pos, key;
printf("创建la:\n");
createSqlist(&Ta);

printf("请输入要查找的数字:");
scanf("%d", &x);
Find(Ta, x);

printf("\n请输入要插入的位置及数字:");
scanf("%d%d", &pos,&key);
insertSqlist(&Ta, pos, key);

Dele(&Ta);
printf("\n创建lb:\n");
createSqlist(&Tb);
printf("\nla lb 合并后:");
Mergelist(&Ta, &Tb, &Tc);
print(Tc);
return 0;

}

你可能感兴趣的:(线性表的顺序实现)