集合的运算之链表实现

#include <iostream>
using namespace std;

struct Node
{
	int content;
	Node *next;
};

Node *input();
void output(Node *);
Node *A_or_B(Node *, Node *);
Node *A_and_B(Node *, Node *);
Node *A_not_B(Node *, Node *);
bool is_a(int, Node *);

int main()
{
	Node *head_A = input();
	Node *head_B = input();
	Node *s1 = A_and_B(head_A, head_B);
	Node *s2 = A_or_B(head_A, head_B);
	Node *s3 = A_not_B(head_A, head_B);
	Node *s4 = A_not_B(head_B, head_A);
	cout << "A and B is: ";
	output(s1);
	cout << "A or B is: ";
	output(s2);
	cout << "A not B is: ";
	output(s3);
	cout << "B not A is: ";
	output(s4);
	return 0;
}

Node *input()
{
	Node *head = NULL, *tail = NULL;
	int x;
	cin >> x;
	while (x != -1)
	{
		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;
}

void output(Node *head)
{
	for (Node *p = head; p != NULL; p = p->next)
		cout << p->content << " ";
	cout << endl;
}

Node *A_and_B(Node *h1, Node *h2)
{
	if (h1 == NULL || h2 == NULL)
		return NULL;
	else
	{
		Node *head = NULL;
		for (Node *h = h2; h != NULL; h = h->next)
			if (is_a(h->content, h1))
			{
				Node *p = new Node;
				p->content = h->content;
				if (head == NULL)
				{
					head = p;
					p->next = NULL;
				}
				else
				{
					p->next = head;
					head = p;
				}
			}
		return head;
	}
}


Node *A_or_B(Node *h1, Node *h2)
{
	if (h1 == NULL)
		return h2;
	else if (h2 == NULL)
		return h1;
	else
	{
		Node *head = NULL, *tail = NULL;
		for (Node *h = h1; h != NULL; h = h->next)
		{
			Node *p = new Node;
			p->content = h->content;
			p->next = NULL;
			if (head == NULL)
				head = tail = p;
			else
			{
				tail->next = p;
				tail = p;
			}
		}
		for (Node *h = h2; h != NULL; h = h->next)
			if (!(is_a(h->content, h1)))
			{
				Node *p = new Node;
				p->content = h->content;
				p->next = NULL;
				if (head == NULL)
					head = tail = p;
				else
				{
					tail->next = p;
					tail = p;
				}
			}
		return head;
	}
}


Node *A_not_B(Node *h1, Node *h2)
{
	if (h1 == NULL)
		return NULL;
	else if (h2 == NULL)
		return h1;
	else
	{
		Node *head = NULL, *tail = NULL;
		for (Node *h = h1; h != NULL; h = h->next)
			if (!(is_a(h->content, h2)))
			{
				Node *p = new Node;
				p->content = h->content;
				p->next = NULL;
				if (head == NULL)
					head = tail = p;
				else
				{
					tail->next = p;
					tail = p;
				}
			}
		return head;
	}
}

bool is_a(int i, Node *head)//此函数判断某一个数是否是一个链表中的结点值
{
	Node *h = head;
	while (h != NULL)
	{
		if (i == h->content)
			return true;
		h = h->next;
	}
	return false;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值