The Joseph ring is a mathematical application of the problem: known n individuals (represented by numbers 1, 2, 3,..., n) sit around a round table. K from a number of people start off, the man out of the line to the m; his next person and from 1 to start off, count to m that another person out; so law be repeated until all of the people out around the table.
#include <iostream>
using namespace std;
struct Node
{
int data;
struct Node* next;
};
int main()
{
int m,n;
Node *head,*rear,*p,*q,*s;
head = new Node;
p = new Node;
rear = head;
cout<<"Please input the number of people:";
cin>>n;
cout<<"Please input the number of people out line:";
cin>>m;
//the head node does't store the data and does only turnover
for(int i=1;i<n+1;++i)
{
s = new Node;
s->data = i;
rear->next = s;
rear = s;
rear->next = head->next;
}
int k = 0;
//record node data
int record=0;
p = head->next;
//the next node of the last is itself
while(p&&p->next!=p)
{
k++;
//when m-1 appeared,delete the it's next node
if(k==(m-1))
{
k = 0;
q = new Node;
q = p->next;
p->next = q->next;
p = p->next; //skip the node to be deleted
record = p->data;
delete q;
}
else
p = p->next;
}
cout<<"result is "<<record<<endl;
return 0;
}