发布网友 发布时间:2022-04-23 05:35
共1个回答
热心网友 时间:2022-04-28 03:54
#include <stdio.h>
#include <stdlib.h>
typedef int DataType; // 定义数据数据类型
typedef struct {
DataType *data; // data指向数据区的首个数据
int length; // 数据长度
}SqList;
void Sort(SqList *L) {
int i,j,k;
DataType tmp;
for(i = 0; i < L->length - 1; ++i) {
k = i;
for(j = i + 1; j < L->length; ++j)
if(L->data[k] > L->data[j])
k = j;
if(k != i) {
tmp = L->data[k];
L->data[k] = L->data[i];
L->data[i] = tmp;
}
}
}
SqList *CreateList(DataType a[],int n) {
int i;
SqList *L;
L = (SqList *)malloc(sizeof(SqList));
L->data = (DataType *)malloc(n * sizeof(DataType));
L->length = n;
for(i = 0; i < n; ++i) L->data[i] = a[i];
Sort(L);
return L;
}
int InsertList(SqList *L,DataType x) {
int i,j;
for (i = 0;i < L->length;i++) {
if(x <= L->data[i]) {
for(j = L->length;j >= i;j--)
L->data[j + 1] = L->data[j]; // 结点后移
L->data[i] = x;
L->length++;
return 1;
}
}
L->data[L->length++] = x;
return 1;
}
int RemoveListElem(SqList *L,DataType d) {
int i,j;
for(i = 0; i < L->length; ++i) {
if(L->data[i] == d) {
for(j = i; j < L->length - 1; ++j)
L->data[j] = L->data[j + 1];
L->length--;
return 1;
}
}
return 0;
}
SqList *AndList(SqList *A, SqList *B) { /* A∩B */
int i,j,k = 0;
int len = (A->length > B->length) ? B->length : A->length;
SqList *C = (SqList *)malloc(sizeof(SqList));
C->length = len;
C->data = (DataType *)malloc(len * sizeof(DataType));
for(i = 0; i < A->length; ++i) {
for(j = 0; j < B->length; ++j) {
if(A->data[i] == B->data[j]) {
C->data[k++] = A->data[i];
break;
}
}
}
C->length = k;
return C;
}
SqList *OrList(SqList *A, SqList *B) { /* A∪B */
int i,j,flag;
DataType e;
SqList *C = (SqList *)malloc(sizeof(SqList));
C->length = A->length + B->length;
C->data = (DataType *)malloc(C->length * sizeof(DataType));
for(i = 0; i < A->length; ++i) C->data[i] = A->data[i];
for(i = 0; i < B->length; ++i) {
e = B->data[i];
flag = 1;
for(j = 0; j < C->length; ++j) {
if(e == C->data[j]) {
flag = 0;
break;
}
}
if(flag) InsertList(C,e);
}
return C;
}
void PrintList(SqList *L) {
int i;
for(i = 0; i < L->length; ++i)
printf("%d ",L->data[i]);
printf("\n");
}
void FreeList(SqList *L) {
free(L->data);
free(L);
}
void main() {
DataType x;
DataType arra[] = {36,24,31,5,90,65,70,39,37};
DataType arrb[] = {9,8,43,51,37,,33,46,29,80,56};
int alen = sizeof(arra)/sizeof(arra[0]);
int blen = sizeof(arrb)/sizeof(arrb[0]);
SqList *A = CreateList(arra,alen);
printf("A线性表为: ");
PrintList(A);
SqList *B = CreateList(arrb,blen);
printf("B线性表为: ");
PrintList(B);
SqList *C = AndList(A,B);
SqList *D = OrList(A,B);
printf(" C = A∩B: ");
PrintList(C);
printf(" D = A∪B: ");
PrintList(D);
printf("在D表中插入数据 : ");
scanf("%d",&x);
InsertList(D,x);
printf("D表插入x后 :");
PrintList(D);
printf("删除D表中数据 : ");
scanf("%d",&x);
RemoveListElem(D,x);
printf("删除x后的D表为 :");
PrintList(D);
FreeList(A);
FreeList(B);
FreeList(C);
FreeList(D);
}
追问我要的是排序的 不是集合