c++链表实现集合交集并集差集运算

#include<iostream>
using namespace std;
//创建链表
struct Node
{
    int content;
    Node* next;
};
//输入集合
Node* input_set()
{
    Node* head = NULL, *tail=NULL;
    int x;
    cin >> x;
    while (x != 10086)
    {
        Node*p = new Node;
        p->content = x;
        p->next = NULL;
        if (head == NULL)head = tail = p;
        else
        {
            tail->next = p;
            tail = p;
        }
        cin >> x;
    }
    return head;
}
//查找
bool find(Node *head, int x)
{
    for (Node *p = head; p != NULL; p = p->next)
        if (p->content == x) return true;
    return false;
}
//添加(从表头插入)
void insert(Node *&head, int x) 
{
    Node *p = new Node;
    p->content = x;
    p->next = head;
    head = p;
}
//交集
Node *intersection(Node *head1,Node *head2)
{
    Node* head = NULL;
    for (Node *p = head1; p != NULL; p = p->next)
    {
        if (find(head2, p->content))insert(head, p->content);
    }
    return head;
}
//并集
Node *_union(Node *head1, Node *head2) 
{
    Node *head = NULL, *p;
    for (p = head1; p != NULL; p = p->next)
        insert(head, p->content);
    for (p = head2; p != NULL; p = p->next)
    {
        if (!find(head1, p->content))insert(head, p->content);
    }
    return head;
}
//差集
Node *difference(Node *head1, Node *head2)
{
    Node *head = NULL, *p;
    for (p = head1; p != NULL; p = p->next)
    {
        if (!find(head2, p->content))insert(head, p->content);
    }
    return head;
}
//输出集合
void output_set(Node *head)
{
    Node *p;
    for (p = head; p != NULL; p = p->next)cout << p->content << " ";
    cout << endl;
}
//删除集合
void _delete(Node *&head)
{
    while(head != NULL)
    {
        Node*p;
        p = head;
        head = head->next;
        delete p;
    }
}
int main()
{
    cout << "请依次输入两个集合的元素(以10086结束)";
    Node *set1,*set2,*set_intersection,*set_union,*difference_set;
    set1=input_set();
    set2 = input_set();
    set_intersection = intersection(set1, set2);
    set_union = _union(set1, set2);
    difference_set = difference(set1, set2);
    cout << "交集是:";
    output_set(set_intersection);
    cout << "并集是:";
    output_set(set_union);
    cout << "差集是:";
    output_set(difference_set);
    _delete(set1);
    _delete(set2);
    _delete(set_intersection);
    _delete(set_union);
    _delete(difference_set);
    return 0;
}

  • 3
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值