7-3 约瑟夫环 (25 分)

很明显这是一个循环链表,当报到这个同学的时候我们把这个同学删除就好了;本蒟蒻的代码有些简陋,还没有及时修改,请见谅

#include 
using namespace std;
#include 
struct Node{

	int data;
	Node*next;
};

int main()
{
	int n, m;
	cin >> n >> m;

	vectorres;
	Node * first = new Node;
	//first->next =nullptr;
	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;

	//cout << "pre->data = " << pre->data <<"p->next = "<data<< endl;

	int cnt = 1;
	for (auto i = pre,j = p;n; i = i->next)
	{


		if (cnt == m)
		{
			auto pr = i;
			res.push_back(i->data);
			//cout << i->data << " ";
			j->next = i->next;
		//delete pr;
			n--;
			cnt = 0;
		}
		cnt++;
		j = i;
		//system("pause");
	}

	bool tf = false;
	for (auto &x : res)
	{
		if (tf)
			cout << " ";
		cout << x;
		tf = true;
	}

	system("pause");
	return 0;
}

 

你可能感兴趣的:(PTA,题解)