I. Description of the problem
The existing n mice in a circle, a cat from any place to eat mice, every time a mouse to eat, please give the last mouse number? The title requirement is to give the mouse number n, output the cat last eat the mouse number.
Second, problem solving
We assume that there are N mice, the sequence number is 1,2,3,......, n-1,n, and the serial number is clockwise in a circle.
The structure of the mouse information is defined as follows, using a two-way list, as follows:
typedef struct MouseNode
{
int nNO;
MouseNode *pNext;
MouseNode *pPre;
MouseNode() { nNO = 0; pNext = NULL; pPre = NULL; }
MouseNode(int NO) { nNO = NO; pNext = NULL; pPre = NULL; }
}MouseNode;
My algorithm has only one function, and this function completes eating a circle of mice. The incoming parameter is the first mouse to be eaten in a two-way list, and the return value is the first mouse to eat when the mouse is eating the next lap.
The function code is as follows:
Cateatmouses
/*
This function only eats a circle of mice and loops to call it to eat the mouse
Parameters this secondary eaten mice
Back to the next lap, the first mouse to eat when the mouse
If the return value is empty, the mouse has finished eating
*/
Mousenode *cateatmouses (Mousenode *pstartmouse)
{
Mousenode *pfirst = Pstartmouse;
Mousenode *pfirstnoteatmouse = pfirst->pnext;
if (Pfirst = = Pfirstnoteatmouse)
{
printf ("%d", Pfirst->nno);
return NULL; Finished eating
}
bool Bcaneat = true;
while (true)
{
if (Pfirst = = Pfirstnoteatmouse)
{
if (bcaneat)
{
return pfirstnoteatmouse;
}
Else
{
Return pfirstnoteatmouse->pnext;
}
}
if (bcaneat)
{
Pfirst->ppre->pnext = pfirst->pnext;
Pfirst->pnext->ppre = pfirst->ppre;
printf ("%d", Pfirst->nno);
Pfirst = pfirst->pnext;
Bcaneat = false;
}
Else
{
Pfirst = pfirst->pnext;
}
}
}