栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

#include
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;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/779271.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号