C + + String programming training 2

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.