c语言链表实现两集合的交集(1)

个人博客网站: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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值