题目描述
有n人围成一圈,顺序排号。从第1个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来的第几号的那位。
输入
初始人数n
输出
最后一人的初始编号
样例输入
3
样例输出
2
`方法:建立一个循环链表,封三删除一个节点,直到剩下一个节点为止
在这里插入代码片
#include <stdio.h>
#include <stdlib.h>
struct Ring{
int num;
struct Ring *next;
};
void creat(int n){
int i;
struct Ring* temp1,*pre;
struct Ring *pNew,*pEnd,*pHead=NULL;
pEnd=(struct Ring*)malloc(sizeof(struct Ring));
// 创建链表
for(i=0;i<n;i++){
pNew=(struct Ring*)malloc(sizeof(struct Ring));
pNew->num=i+1;
if(i==0){
pHead=pNew;
pNew->next=pHead;
}
else{
pNew->next=pHead;
pEnd->next=pNew;
}
pEnd=pNew;
}
//删除链表
pre=pEnd;
int count=n;
while(count!=1){
for(i=0;i<3;i++){
if(i==0||i==1){
pre=pre->next;
temp1=pre->next;
}
else {
pre->next=temp1->next;
free(temp1);
count--;
}
}
}
printf("%d",pre->num);
}
int main(){
int n;
scanf("%d",&n);
creat(n);
return 0;
}