链表之报数问题
描述
有n个人围成一圈,顺序从1开始排号。从第1个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。建议用循环链表实现。
链表节点结构体:
typedef struct Node
{
int num;
struct Node* next;
};
输入
只有一个正整数n,(其中n的范围n>=3,n<=1000)。
输出
输出最后留下的人是原来的第几号。
请注意行尾输出换行。
输入样例 1
10
输出样例 1
4
输入样例 2
50
输出样例 2
11
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int num;
struct node *next;
}human;
human *head,*node,*tail;
void create(int n){ //创建链表
node=(human*)malloc(sizeof(human));
node->num=1;
head=node;
tail=node;
head->next=NULL;
for(int i=0;i<n-1;i++){
node=(human*)malloc(sizeof(human));
node->num=i+2;
tail->next=node;
tail=node;
}
tail->next=head;
}
int main(){
int n;
int count=1; //计数器
int num;
human *tmp;
scanf("%d",&n);
create(n);
tmp=head; //注意!要create链表了之后才能将tmp指向head
while(1){
tmp=tmp->next;
count++;
if((count+1)%3==0){ //这里删除的条件是count到3之前,因为该链表是单向链表,必须从前一项开始
tmp->next=tmp->next->next;
count=0; //将计数器清零
}
if(tmp->next==tmp->next->next){ //这里循环结束的条件是只剩下两个节点
printf("%d",tmp->num);
break;
}
}
}