#include <iostream>
using namespace std;
typedef int Elemtype;
typedef struct ListNode
{
Elemtype data;
ListNode *next;
}ListNode;
ListNode* CreateList(ListNode *&first,int n)
{
ListNode *last=new ListNode;
int i;
last=first;
first->next=last;
last->next=first;
last=first;
Elemtype temp;
for(i=0;i<n;++i)
{
temp=i+1;
ListNode *newnode=new ListNode;
newnode->data=temp;
newnode->next=NULL;
newnode->next=last->next;
last->next=newnode;
last=newnode;
}
return first;
}
void Delete(ListNode *&first,int n,int m) //n表示次数,m表示编号
{
int i,j;
ListNode *head=new ListNode;
ListNode *current=new ListNode;
ListNode *pre=new ListNode;
ListNode *temp=new ListNode;
head=first;
pre=first;
current=pre->next;
for(i=0;i<n;++i)
{
for(j=0;j<m-1;++j)
{
if(current->next==head)
current=current->next;
pre=current;
current=current->next;
}
pre->next=current->next;
temp=current;
cout<<"出列的人编号:"<<temp->data<<endl;
current=current->next;
if(current==head)
current=current->next;
delete temp;
}
}
void Display(ListNode *first)
{
ListNode *current;
current=first->next;
while (current!=first)
{
cout<<current->data<<" ";
current=current->next;
}
}
int main()
{
ListNode *first=new ListNode;
first->next=NULL;
int i,n,m;
cout<<"约瑟夫问题测试"<<endl;
cout<<"请输入人数的总数"<<endl;
cin>>i;
first=CreateList(first,i);
cout<<"请输入循环次数和以几为一次循环的号码"<<endl;
cin>>n>>m;
Delete(first,n,m);
cout<<"剩下的人编号分别是:"<<endl;
Display(first);
system("pause");
return 0;
}