7-3 约瑟夫环 (25 分)-数据结构第2章

#include 
using namespace std;
#include 
struct Node{

	int data;
	Node*next;
};

int main()
{
	int n, m;
	cin >> n >> m;
	vectorres;
	Node * first = new Node;
	Node *pre = new Node;
	Node * p = new Node;

	pre = first;
	pre->next = p;
	p = first;
	if (n)
	{
		pre->data = 1;
	}
	for (int i = 2; i <= n; i++)
	{
		Node * pc = new Node;
		pc->data = i;
		pc->next = nullptr;
		p->next = pc;
		p = pc;
	}
	p->next = pre;
	int cnt = 1;
	for (auto i = pre,j = p;n; i = i->next)
	{


		if (cnt == m)
		{
			auto pr = i;
			res.push_back(i->data);
			j->next = i->next;
			n--;
			cnt = 0;
		}
		cnt++;
		j = i;
	}

//	这里是担心行尾有空格,而出现的格式错误,所以我把那些首先删除的人存到容器中,然后再删除; 
	bool tf = false;
	for (auto &x : res)
	{
		if (tf)
			cout << " ";
		cout << x;
		tf = true;
	}
	system("pause");
	return 0;
}

 

你可能感兴趣的:(数据结构PTA,题解)