个人博客网站:https://www.liuzhi.org.cn/
#include <stdio.h>
#include <malloc.h>
typedef struct node {
int num;
struct node *next;
}AGG;
AGG *CreateList() { // 创建单循环链表,返回链表头
AGG *head,*p;
int i,n;
printf("结点个数n = ");
scanf("%d",&n);
head = p = (AGG *)malloc(sizeof(AGG)); // 专用头结点
head->num = 0;
printf("输入 %d 整数(空格隔开):\n",n);
for(i = 0; i < n; ++i) {
p->next = (AGG *)malloc(sizeof(AGG));
scanf("%d",&p->next->num);
p = p->next;
}
p->next = head;
return head;
}
AGG *MutualAgg(AGG *A,AGG *B) { // A∩B
AGG *C,*pa,*pb,*pc,*qc;
C = pc = (AGG *)malloc(sizeof(AGG));
pc->num = 0;
pa = A->next;
pb = B;
while(pa != A) {
pb = B->next;
while(pb != B) {
if(pb->num == pa->num) {
qc = (AGG *)malloc(sizeof(AGG));
qc->num = pb->num;
pc->next = qc;
pc = qc;
}
pb = pb->next;
}
pa = pa->next;
}
pc->next = C;
return C;
}
void PrintList(AGG *head) {
AGG *p = head->next;
short counter = 0;
while(p != head) {
if(counter && counter%10 == 0) printf("\n");
printf("%5d",p->num);
counter++;
p = p->next;
}
if(counter % 10) printf("\n");
}
void freeheap(AGG *head) {
AGG *p,*q;
p = head;
q = p->next;
while(q != head) {
p = q;
q = p->next;
free(p);
}
free(head);
}
int main() {
AGG *A,*B,*C,*D,*E;
printf("创建集合 A:\n");
A = CreateList();
printf("创建集合 B:\n");
B = CreateList();
printf("集合A的元素有:\n");
PrintList(A);
printf("集合B的元素有:\n");
PrintList(B);
C = MutualAgg(A,B);
printf("交集 C = A∩B:\n");
PrintList(C);
freeheap(A);
freeheap(B);
freeheap(C);
printf("\n\n");
return 0;
}