Joseph problem(模拟)

#include<iostream>
using namespace std;
struct Node
{
	Node();
	Node(int item, Node *add_on = NULL);
	Node *next;
	int entry;
};

Node::Node()
{
	next = NULL;
}

Node::Node(int item, Node * add_on)
{
	entry = item;
	next = add_on;
}

void main() {
	while (1) {
		int n, m, k;
		cout << "please enter the num of the people." << endl;
		cin >> n;
		cout << "please enter the ID of people to begin." << endl;
		cin >> k;
		cout << "please enter the count to exit." << endl;
		cin >> m;
		cout << "leaving order:";
		Node *head = new Node(1);
		Node *p = head;
		for (int i = 2; i <= n; i++) {//生成链表
			p->next = new Node(i);
			p = p->next;
		}
		p->next = head;
		for (int i = 1; i < k; i++, p = p->next);
		while (n != 1) {
			for (int i = 0; i < m - 1; i++, p = p->next);
			Node *temp = p->next;
			p->next = temp->next;
			cout << temp->entry << ' ';
			delete temp;
			n--;
		}
		cout << endl<<"the winner is " << p->entry << endl;
	}
}

你可能感兴趣的