题目:13个人围成一圈,从第1个人开始顺序报号1,2,3。凡报到3者退出圈子。找出最后留在圈子中的人原来的序号。要求用链表实现。
#include<stdio.h>
#define NUM 13
typedef struct people{
int num;
struct people *next;
}people; //people相当链表中的LNode
int main(){
int count = NUM,i;
people p[NUM],*head=p;//head指向p[0]
for(i=0;i<NUM;i++){
head->num = i+1;
head->next = &p[i+1];
head = head->next;
}
p[NUM-1].next = p; //最后一个元素指向第一个元素
head = p;
i=1;
while(count>1){
if(head->num==0){
head = head->next;
continue;
}
if(i==3){
printf("%d被淘汰\n",head->num);
head->num = 0;
count--;
}
head = head->next;
i++;
if(i>3) i=1;
}
//不为0的就是最后留下来的。
while(head->num==0){
head = head->next;
if(head->num!=0)
printf("留到最后的是%d\n",head->num);
}
return 0;
}
结果:
![](https://img-blog.csdnimg.cn/img_convert/231635d1c3d16fec44b7ac2f0f6108e4.png)