链表解决约瑟夫环(Josephus)问题

这里存储的出列的序列,如果只想要最后一人输出res[n-1]就好了

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

void Josephus(int n, int m, int res[])
{
	if( n<=0 || m<=0 )
		return;
	
	list<int> List;    //链表	
	int i, cnt = 0;
	for(i = 1; i <= n; ++i)
		List.push_back(i);
	
	list<int>::iterator t, it = List.begin();		 
	for(i = 0; i < n; ++i){
		int step = m%n;	//若出现m>n的情况 
		while( step-- ){
			t = it;		//t是要删除的结点,it指向下一个结点
						//直接对it earse操作会发生迭代器异常 
			if( it == --List.end() )
				it = List.begin();
			else	
				++it;
		}
		res[i] = *t;
		List.erase(t);
	}
}

int main()
{	
	int n = 7, m = 3;
	int res[n];
	Josephus(n, m, res);
	
	for(int i = 0; i < n; ++i)
		cout << res[i] << " ";
	cout << endl;
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Love_Irelia97/article/details/82584917