不敢死队问题
2016-08-04 21:12
281 查看
这道题的算法思想就是构建一个循环链表,然后将排长设为头结点,设置一个标记变量k,用来记录走过的结点数,当结点数等于5的倍数时,判断当前结点是不是头结点,若是,则输出k/5;若不是,则删除当前结点,继续循环。
代码如下:
#include <stdio.h>
#include <malloc.h>
struct node{
int data;
struct node* next;
};
struct node* Createlist(int n){/*创建一个循环链表*/
struct node* head,*tail,*p;
int i;
head=(struct node*)malloc(sizeof(struct node));
head->data=1;/*头结点的值域不为空*/
head->next=NULL;
tail=head;
for(i=2;i<=n;i++){
p=(struct node*)malloc(sizeof(struct node));
p->data=i;
p->next=NULL;
tail->next=p;
tail=p;
}
tail->next=head;/*将尾指针指向头结点,构成循环链表*/
return head;
};
int main(){
int n,k;
struct node* head,*p,*t;
while(scanf("%d",&n)!=EOF&&n!=0){
head=Createlist(n);
for(p=head,k=1;;p=p->next,k++){/*k为标记标量,用来记录指针走过的结点数*/
if(k%5==0){/*当k对5取余等于0时,要么派出排长,要么删掉当前结点*/
if(p->data==1){
printf("%d\n",k/5);
break;
}
else{
t=head;
while(t->next!=p)/*寻找当前结点的前一个结点*/
t=t->next;
t->next=p->next;/*删除当前结点*/
}
}
}
}
return 0;
}