C++打印两个有序链表的公共部分

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wx1458451310/article/details/88081676

C++打印两个有序链表的公共部分

cede:

#include <iostream>
#include <list>
#include <iterator>
using namespace std;

int main()
{
	int m,n,temp;
	//输入两个链表的长度m,n
	cin>>m>>n;
	list<int> a;
	list<int> b;

	//向链表a和b中放元素
	for (int i=0;i<m;i++)
	{
		cin>>temp;
		a.push_back( temp );
	}

	for (int i=0;i<n;i++)
	{
		cin>>temp;
		b.push_back(temp);
	}
	//使链表有序
	a.sort();
	b.sort();
	//类似外排的方法来找出公共部分
	list<int>::iterator p = a.begin();
	list<int>::iterator q = b.begin();

	while( p!=a.end() && q!=b.end())
	{
		if(*p < *q)
			p++;
		else if(*p > *q)
			q++;
		else
		{
			cout<<*p<<" "<<endl;
			p++;
			q++;
		}
	}

	system("pause");
	return 0;
 }

猜你喜欢

转载自blog.csdn.net/wx1458451310/article/details/88081676