C 顺序表求交集和并集

来源:互联网 发布:linux maven 打包war 编辑:程序博客网 时间:2024/06/07 06:45
#include<stdio.h>
#include<stdlib.h>
typedef struct {
    int *array;//线性表记录数据
    int length;
}List;
int isExist(List src, int tmp)
{
    int i = 0;
    while (i < src.length)
    {
        if (src.array[i] == tmp)
            break;
        i++;
    }
    if (i == src.length)
        return 0;    //不存在
    return 1;  //存在
}

List unionList(List src1, List src2)
{
    List des;
    int i;
    des.array = (int *)malloc(sizeof(int)*(src1.length + src2.length));
    des.length = 0;
    for (i = 0;i < src1.length;++i) //将src1中的数据加到输出集合中
    {
        if (!isExist(des, src1.array[i]))
        {
            des.array[des.length] = src1.array[i];
            des.length++;
        }
    }
    for (i = 0;i < src2.length;++i) //将src2中的数据加到输出集合中,没有写到一起,上下基本一样,方便记忆
    {
        if (!isExist(des, src2.array[i]))
        {
            des.array[des.length] = src2.array[i];
            des.length++;
        }
    }
    return des;//返回并集
}

List sectionList(List src1, List src2)
{
    List des;
    int i;
    int len = src1.length < src2.length ? src1.length : src2.length;  //去两个集合中较大的集合的个数,因为是交集
    //可以直接改成  int len = src1.length;  这样简单方便记忆
    des.array = (int *)malloc(sizeof(int)*(len));
    des.length = 0;
    for (i = 0;i < src2.length;i++) //将src1和src2的交集输出到des中,没有优化,可以根据大小,减少循环次数
    {
        if (isExist(src1, src2.array[i]) && !isExist(des, src2.array[i]))  //src2中的元素存在于src1中,但是不存在des中
        {
            des.array[des.length] = src2.array[i];    //符合条件加入des
            des.length++;
        }
    }
    return des;//返回并集
}
//上面函数中的src1,src2,des相当于  集合A,B,C  
//并集   C = A v B  ,C的最大长度   = A的长度 + B 的长度
//交集   C = A ^ B ,C的最大长度 = A 与 B 中较小的那一个
int main()
{
    
    List A,B;
    int i;   //i没有写到for循环中,怕老版本编译器不兼容
    int a[7] = { 1,2,6,7,8,9,10 };
    int b[6] = { 2,3,6,8,10,12 };
    A.array = a;
    A.length = 7;
    B.array = b;
    B.length = 6;
    List x = unionList(A, B);
    List y = sectionList(A, B);
    printf("A,B 并集:\n");
    for (i = 0;i < x.length;i++)
        printf("%d\t", x.array[i]);
    printf("\n\n\nA,B交集:\n");
    for (i = 0;i < y.length;i++)
        printf("%d\t", y.array[i]);
    printf("\n");

    system("pause");
    return 0;
}
0 0
原创粉丝点击