#include <iostream>
using namespace std;
typedef struct student
{
int data;
struct student* next;
}node,*LinkList;
//約瑟夫環
void printfList(LinkList head){
LinkList p=head;
if (head!=NULL)//忘了這個
{
do{
cout<<p->data<<" ";
p=p->next;
}while(p!=head);//這裏出現過問題,用do-while
cout<<endl;
}
}
void Josephus(int n,int k,int m){
int i=2;
LinkList head=(LinkList)malloc(sizeof(node));
head->next=head;
head->data=1;
LinkList pre=head;
while(i<=n){
LinkList p=(LinkList)malloc(sizeof(node));
p->data=i;
p->next=pre->next;
pre->next=p;
pre=p;
i++;
}
printfList(head);
LinkList mend=pre;
int kk=0;
while(kk!=k){
mend=mend->next;
++kk;
}//找到k個開始
while(n--){//要全部輸出
int mm=1;
pre=mend;//每次都要給pre從新復值否則程序錯誤
while(mm!=m){//不是要求的數,指針每次往前推一步,mend指向報數的人,pre指向前一個
pre=mend;
mend=mend->next;
mm++;
}
pre->next=mend->next;//前一個鏈到下一個準備報數的
cout<<mend->data<<endl;
LinkList deletem=mend;
mend=pre->next;//mend指向報數的人;
free(deletem); //最後刪除
}
}
int main(){
Josephus(13,4,1);
return 0;
}