13个人围成一圈,从第一个人开始顺序报号1,2,3。凡报到3者退出圈子。找出最后留在圈子中的人原来的序号。要求用链表实现。
#include<stdio.h>
#include<stdlib.h>
struct Student{
int num;
struct Student *next;
};
int main(){
struct Student *create();
void play(struct Student *head);
struct Student *head;
head=create();
play(head);
return 0;
}
struct Student *create(){
struct Student *head,*p,*q;
int n=0,i;
p=(struct Student *)malloc(sizeof(struct Student));
scanf("%d",&(p->num));
for(i=0;i<13;i++){
n++;
if(n==1){
head=p;
}else{
q->next=p;
}
q=p;
p=(struct Student *)malloc(sizeof(struct Student));
scanf("%d",&(p->num));
}
q->next=NULL;
return head;
}
void play(struct Student *head){
struct Student *p,*q;
q=head;
int sum=13,n=1;
while(sum!=1){
while(q!=NULL){
if(n==3&&q==head){
head=q->next;
sum--;
n=0;
}else if(n==3){
p->next=q->next;
sum--;
n=0;
}
p=q;
q=q->next;
n++;
}
q=head;
}
printf("%d",head->num);
}
这段是用的动态链表实现的,其实更好的办法使用循环链表,但是这道题目是谭浩强C语言书的课后习题,书上并未提及循环链表的使用方法,所以我就没有使用。
感谢各位大佬观看,欢迎批评指正!