顺序表实现集合差集 c语言代码
时间: 2024-05-31 16:07:39 浏览: 74
#include <stdio.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int length;
}SqList;
void InitList(SqList *L) {
L->length = 0;
}
int LocateElem(SqList L, int e) {
int i;
for (i = 0; i < L.length; i++) {
if (L.data[i] == e) {
return i;
}
}
return -1;
}
void ListInsert(SqList *L, int i, int e) {
if (L->length == MAXSIZE) {
printf("List is full.\n");
return;
}
if (i < 1 || i > L->length + 1) {
printf("Insert position is error.\n");
return;
}
for (int j = L->length - 1; j >= i - 1; j--) {
L->data[j + 1] = L->data[j];
}
L->data[i - 1] = e;
L->length++;
}
void ListDelete(SqList *L, int i) {
if (L->length == 0) {
printf("List is empty.\n");
return;
}
if (i < 1 || i > L->length) {
printf("Delete position is error.\n");
return;
}
for (int j = i; j < L->length; j++) {
L->data[j - 1] = L->data[j];
}
L->length--;
}
void PrintList(SqList L) {
for (int i = 0; i < L.length; i++) {
printf("%d ", L.data[i]);
}
printf("\n");
}
void Difference(SqList *La, SqList Lb) {
int i;
for (i = 0; i < La->length; i++) {
if (LocateElem(Lb, La->data[i]) != -1) {
ListDelete(La, i + 1);
i--;
}
}
}
int main() {
SqList La, Lb;
InitList(&La);
InitList(&Lb);
ListInsert(&La, 1, 1);
ListInsert(&La, 2, 2);
ListInsert(&La, 3, 3);
ListInsert(&La, 4, 4);
ListInsert(&La, 5, 5);
ListInsert(&Lb, 1, 3);
ListInsert(&Lb, 2, 4);
ListInsert(&Lb, 3, 6);
printf("La: ");
PrintList(La);
printf("Lb: ");
PrintList(Lb);
Difference(&La, Lb);
printf("La - Lb: ");
PrintList(La);
return 0;
}
阅读全文