A systematic algorithm for cats eating mice

Source: Internet
Author: User
Tags printf

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

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.