现在的位置: 首页 > 综合 > 正文

约瑟夫环问题

2014年02月22日 ⁄ 综合 ⁄ 共 586字 ⁄ 字号 评论关闭
问题描述,100个猴子,排好队后,从1开始编号,然后开始报数,从1开始数到7的猴子退出,一直循环,问剩下的猴子是哪个?

这个问题就是一个简单的队列,入队出队问题,下面是代码实现

void monkeyTest() { node *head,*p,*tail; head = (node *)malloc(sizeof(node)); head->data = 1; head->next = NULL; tail = head; //初始化队列   for(int i=2; i<=100; i++){ p = (node *)malloc(sizeof(node)); p->data = i; p->next = NULL; tail->next = p; tail = p; } tail->next = head; head = count(head); printf("the king is %d\n",head->data); free(head); } node *count(node *head) { node *p = head; while(p->next != p){ for(int i=1; i<7; i++){ p = p->next; } deleteNode(p); } return p; } void deleteNode(node *cur) { node *next = cur->next; cur->data = next->data; cur->next = next->next; free(next); }

抱歉!评论已关闭.