Monkey said dawang problem Algorithm

Source: Internet
Author: User
Question: a bunch of monkeys have numbers. The number is 1 , 2 , 3 .. m , This group of monkeys ( M According 1-m From the first 1 Start number, count to the second N The monkey is about to leave this circle, so that it goes down in turn until there is only the last monkey in the circle, then the monkey is king .

Solution: a circleM is regarded as a circular linked list of monkeys, moving from the first node (monkey) to the nth node (monkey) and deleting it, then move from the next node (monkey) and count again from 1 ...... Until there is only one node (monkey) in the circular linked list)

AlgorithmDescription:

Linknode * Cl; // defines a cyclic table pointing to the header node.

Linknode * TCL; // defines a temporary pointer.

TCL = Cl; // point to the header Node

While (lenth (* Cl)> 1) // until the linked list length is 1

{

For (INT I = 1; I <= N; I ++) // numbers 1-N

{

If (I! = N)

{TCL = TCL-> next;} // the pointer is not moved n back.

Else // n

{

Printf: TCL-> next-> num monkey leaves. // the monkey with the serial number num leaves.

TCL-> next = TCL-> next; // Delete the node

TCL = TCL-> next; // move to the next

CL = TCL; // re-specify the loop list header Node

}

}

}

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.