#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct Node {
int no;
Node *next;
} Node;
/**
* 初始化LinkedList
*/
void initLinkedList(Node *head){
head->no = 1;
}
/**
*打印当前循环列表的元素
*/
void procOutputLinkedList(Node *head,int num){
Node *p = head;
int count = 1;
while(count <= num){
cout<<p->no<<" \n";
p = p->next;
}
}
/**
*创建链表
*/
void createLinkedList(Node *head,int num) {
initLinkedList(head);
Node *p = head;
for(int i = 2 ; i <= num ; i ++){
Node * newNode = (Node*)malloc(sizeof(Node));
newNode->no = i;
p->next = newNode;
newNode->next = head;
p = newNode;
}
//procOutputLinkedList(head,rear);
}
/**
*处理约瑟夫出圈
*/
void procJosephus(Node *head,int no,int num) {
Node *p = head;
Node *pPrev = NULL;
int count = 1;
while(p->next != NULL){
if(count == no){
Node *freeP = p;
cout<<p->no<<"\n";
if(num == 2)
pPrev->next = NULL;
else
pPrev->next = p->next;
p = p->next;
free(freeP);
count = 1;
num--;
}else{
pPrev = p;
p = p->next;
count++;
}
}
}
int main() {
Node *head = (Node*) malloc(sizeof(Node));
int num;
int no;
cout<<"请输入约瑟夫出圈问题总人数,出圈序号\n";
cin>>num>>no;
createLinkedList(head,num);
//procOutputLinkedList(head,num);
procJosephus(head,no,num);
return 0;
}