C 順序表求交集和並集

#include
#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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章