約瑟夫環----C鏈表實現
#include<stdio.h>
#include<stdlib.h>
struct list{
int data;
struct list *next;
};
typedef struct list list_node;
int main(){
int size,number,j=0;
scanf("%d %d",&size,&number);
list_node *head,*p,*q;
head=(list_node*)malloc(sizeof(list_node));
head->data=1;
head->next=NULL;
p=head;
for(int i=1;i<size;i++){
p->next=(list_node*)malloc(sizeof(list_node));
p=p->next;
p->data=i+1;
}
p->next=head;
p=p->next;
while(p->next!=p){
j++;
q=p;
p=p->next;
if(j==number-1){
j=0;
q->next=p->next;
printf("%d ",p->data);
free(p);
p=q->next;
}
}
if(p->next=p){
printf("%d",p->data);
}
}