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
}
}
}