c语言用链表写了一个约瑟夫环的问题,不知道错哪了,求大佬解答。
//一个自定义人数,每三人剔除一个。#include<stdio.h>
#include<stdlib.h>
int main(){
struct node{
int num;
struct node* next;
};
typedef struct node node;
node* head,*p,*q;
head = (node*)malloc(sizeof(node));
head->num = -1;
head->next = head;
printf("请输入人数;\n");
int i;
scanf("%d",&i);
for( ;i>0;i--){//建立链表
p = (node*)malloc(sizeof(node));
p->num = i;
p->next = head->next;
head->next = p ;
}
while(p->next!=head){
p = p->next;
}
p->next = head->next;
int k,j;
for(j=0; j<i-1;j++){
for( k=1; k<3; k++){
p = p->next;
}
q = p->next;//要释放的是q
p->next = q->next;
free(q);
}
printf("最终剩下的人%d",p->num);
return 0;
}