做个循环列表就行了。
逻辑上想想还是很简单的。
然而在实践的时候需要考虑许多边界情况。每次循环的时候要考虑头节点的问题。
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
typedef struct node qlist;
int main(){
qlist* head=(qlist*)malloc(sizeof(qlist));
head->data=-1;
head->next=head;
qlist* front=head;
qlist* tail=front;
int n,q,m;
while(scanf("%d %d %d",&n,&q,&m) != EOF){
if(n==0) break;
for(int i=1;i<=n;i++){
qlist* tem=(qlist*)malloc(sizeof(qlist));
tem->data=i;
if(front==head){
head->next=tem;
tem->next=head;
tail=tem;
front=tem;
}else{
tail->next=tem;
tem->next=head;
tail=tem;
}
}
qlist* x =head;
while(front->data!=q){
x=front;
front=front->next;
}
int flag=0;
while(head->next!=head){
for(int i=1;i<m;i++){
x=front;
front=front->next;
if(front==head) {
x=front;
front=front->next;
}
}
if(!flag){
printf("%d",front->data);
flag=1;
}else{
printf(",%d",front->data);
}
qlist* tem2=front;
x->next=front->next;
front=front->next;
if(front==head){
front=front->next;
}
free(tem2);
}
printf("\n");
}
return 0;
}
结果如下:
标签:head,tem,int,3254,next,No.2,front,约瑟夫,qlist From: https://www.cnblogs.com/llllmz/p/17971193