您的位置:首页 > 其它

7、一个链表中的元素由另一个链表实现

2013-11-29 14:50 211 查看
/*7.给定一个链表L和另一个链表P,他们包含以升序排列的整数。

操作printLots(L,P)将打印出L中那些由P所指出的位置上的元素。

例如:如果P=1,3,4,6,那么L中的第1,3,4和6个元素被打印出来。

写出过程printLots(L,P)。该过程的运行时间是多少?

*/
#include<iostream>
#include<list>

using namespace std;

void printLots(const list<int> & P,const list<int> & L){
	if(P.empty() || L.empty() || P.back() > L.size())	//P and L should not be empty,
		return;											//the max number in P must be bigger than L.size();
	
	list<int>::const_iterator con_iterP = P.begin();
	list<int>::const_iterator con_iterL = L.begin();
	int i = 0;

	for(;con_iterP != P.end();con_iterP++){		//cout the element be defined in P
		while(i != *con_iterP){
			i++;
			con_iterL++;
		}

		cout << *con_iterL << endl;
	}

}

int main(){
	
	list<int> L;
	list<int> P;

	L.push_back(1);
	L.push_back(3);
	L.push_back(4);
	L.push_back(6);

	P.push_back(1);
	P.push_back(2);
	P.push_back(3);
	P.push_back(4);
	P.push_back(5);
	P.push_back(6);
	P.push_back(7);

	printLots(L,P);
	
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐