问题
【Q】 一群猴子,编号是1,2,3 …m,这群猴子(m个)按照1~m的顺序围坐一圈。从第1只开始数,每数到第n个,该猴子就要离开此圈,这样依次下来,直到圈中只剩下最后一只猴子,则该猴子为大王。输入m和n,输出为大王的猴子是几号。
代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
int data;
struct node* next;
} linkList;
int main(void)
{
int i = 0;
int allNum = 10, outNum = 4, kingNum;
linkList* pCurrent;
linkList* pNew;
linkList* pHead;
pHead = (linkList*)malloc(sizeof(linkList));
pCurrent = pHead;
pCurrent->data = 1;
pCurrent->next = pCurrent;
for (i = 2; i <= allNum; i++)
{
pNew = (linkList*)malloc(sizeof(linkList));
pNew->data = i;
pNew->next = pCurrent->next;
pCurrent->next = pNew;
pCurrent = pCurrent->next;
}
pCurrent = pHead;
int total = allNum;
linkList* pBefore;
linkList* pDelete;
pBefore = pHead;
while (total != 1)
{
for (i = 1; i < outNum; i++)
{
pCurrent = pCurrent->next;
}
printf("要删除的猴子是:[%d] 号\n", pCurrent->data);
while (pBefore->next != pCurrent)
{
pBefore = pBefore->next;
}
pBefore->next = pCurrent->next;
pDelete = pCurrent;
pCurrent = pCurrent->next;
free(pDelete);
total--;
}
printf("\n\n猴王是:[%d] 号\n\n", pCurrent->data);
free(pCurrent);
return 0;
}
结果
|