Today, an exercise is a very classic Joseph ring problem, in fact, LZ for some of the operation of the list is not too understand, so in some areas of the program is not too much to understand, here to learn from the online practice, also please Daniel can answer my doubts, thank you!
Title: Joseph Ring
Description: Joseph ring is such a problem: known n individuals (number 1, 2, ...) N) sit around the round table. From the number of people began to count K, the number of people in the M-out, his next person from 1 began to count, the number of M of people out, until everyone out.
struct node{
int num;
Node *next;
};
node *creat (int n)//build a linked list, i.e. head-"1-" 2-"... -"N, and finally n back to head."
{
Node *p,*q,*head=null;
for (int i=0;i<=n;i++)
{
P=new node;
p->num=i;
if (head==null)
{
Head=p; Head is indicated by the
}
Else
{
q->next=p;
}
Q=p;
}
p->next=head; P becomes the last node
return p;
}
int main ()
{
int n,k,m;//n is the total number of people, K is the number of the person who began to count, M for reporting the need to dequeue
cin>>n>>k>>m;
Node *l,*q;
L=creat (n);//l is the resulting linked list
q=l;l=l->next;
for (int i=1;i<k;i++)//This step doesn't really understand what it means
{
Q=l;
l=l->next;
}
while (l->next!=l)//l->next==l means only the last person left.
{
for (int i=1;i<m;i++)//If you have not yet checked in, loop through
{
Q=l;
l=l->next;
}
cout<<l->num<< "--";//The number of people who output the dequeue
q->next=l->next;//to delete the man's position.
Delete L;
l=q->next;//with the next person in the dequeue instead of the man out.
}
cout<<l->num;
Delete L;
}
C + + String programming training 2