Intersect交集

Description

 设计一个求集合交的算法:输入集合A与集合B,求集合A与B之交。集合中的元素为整数(可以用c语言中的int表示),且互不相同。

Input

 输入第一行为一个整数t(0<t<10),表示测试用例个数。
每个测试样例由3行构成。第1行是2个正整数a(1≤a≤1000000),b(1≤a≤1000000),分别表示集合A和B的元素个数;第2行为a个以空格分隔的整数,为集合A中元素;第3行为b个以空格分隔的整数,为集合B中元素。

Output

 每个样例单独一行输出交集中元素的个数。

Sample Input
 Copy sample input to clipboard
2
7 5
0 1 2 4 7 8 9
1 2 5 6 7
7 8
1 2 3 4 5 6 8
1 2 4 5 6 7 8 9
Sample Output
3
6

#include<iostream>
using namespace std;

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

Node* Create(int n)
{
	Node* head = new Node;
	Node*p, *pre;
	head->next = NULL;
	pre = head;
	int k;
	for (int i = 1; i <= n; i++)
	{
		p = new Node;
		cin >> k;
		p->data = k;
		p->next = NULL;
		pre->next = p;
		pre = p;
	}
	return head;
}

void jiao(Node*A, Node*B)
{
	Node*p1, *p2;
	p1 = A->next;
	int count = 0;
	while (p1)
	{
		p2 = B->next;
		while (p2)
		{
			if (p2->data == p1->data)
			{
				count++;
				break;
			}
			p2 = p2->next;
		}
		p1 = p1->next;
	}
	cout << count << endl;
}

int main()
{
	int m;
	cin >> m;
	while (m-->0)
	{
		int n1, n2;
		cin >> n1 >> n2;
		Node*A = Create(n1);
		Node*B = Create(n2);
		jiao(A, B);
		delete A, B;
	}

	return 0;
}

  

posted @ 2016-09-26 20:22  KennyRom  阅读(199)  评论(0编辑  收藏  举报