浙大PTA求集合交集

求整数集合A与整数集合B的交集。

输入格式:
输入有三行: 第一行是A和B的元素个数m和n; 第二行是集合A的m个元素; 第三行是集合A的n个元素。

输出格式:
输出交集的所有元素(按照在A集合出现的顺序输出,最后一个输出后面没有空格)。

输入样例:
在这里给出一组输入。例如:

3 4
10 9 2
9 10 8 0

输出样例:
在这里给出相应的输出。例如:

10 9

ac代码:

#include <iostream>

using namespace std;
typedef struct LNode * List;
struct LNode{
    int Data;
    struct LNode * Next;
};

List ReadList(int n);
List Intersection(List L1, List L2);
void PrintList(List L);

int main()
{
    List L1, L2, L;
    int e1, e2;
    scanf("%d%d", &e1, &e2);
    L1 = ReadList(e1);
    L2 = ReadList(e2);
    L = Intersection(L1, L2);
    PrintList(L);
    return 0;
}

List ReadList(int n)
{
    List L, head, s;
    L = (List)malloc(sizeof(struct LNode));
    head = L;
    for(int i = 1; i <= n; i++){
        int e;
        scanf("%d", &e);
        s = (List)malloc(sizeof(struct LNode));
        s->Data = e;
        s->Next = NULL;
        L->Next = s;
        L = L->Next;
    }
    L = head->Next;
    free(head);
    return L;
}
List Intersection(List L1, List L2)
{
    List L, t1, t2, s, head;
    t1 = L1, t2 = L2;
    L = (List)malloc(sizeof(struct LNode));
    L->Next = NULL;
    head = L;
    while(t1){
        t2 = L2;
        while(t2){
            if(t2->Data == t1->Data){
                s = (List)malloc(sizeof(struct LNode));
                s->Data = t1->Data;
                s->Next = NULL;
                L->Next = s;
                L = L ->Next;
                break;
            }
            t2 = t2->Next;
        }
        t1 = t1->Next;
    }
    L = head->Next;
    free(head);
    return L;
}
void PrintList(List L)
{
    if(L == NULL)
        printf("\n");
    else{
        printf("%d", L->Data);
        L = L->Next;
        while(L){
            printf(" %d", L->Data);
            L = L->Next;
        }
    }
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值