约瑟夫环问题

来源:互联网 发布:淘宝赠送的手机支架 编辑:程序博客网 时间:2024/06/05 14:28

问题描述,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);}