链表实现约瑟夫环问题
#include<iostream>
using namespace std;
typedef int ElemType;
typedef struct List
{
ElemType data;
struct List *next;
}LinkNode,*LinkList;
LinkNode *creat_List(int number)
{
LinkList first=new LinkNode;
first->data=-1;
LinkList p=first;
if(first==NULL)
{
cout<<"分配内存失败"<<endl;
exit(0);
}
cout<<"请输入相应数据"<<endl;
for(int i=0;i<number;i++)
{
p->next=new LinkNode;
cin>>p->next->data;
p=p->next;
}
p->next=first;
return p;
}
void deal(LinkList&real,int number)
{
int tag=0;
LinkNode *p;
while(number>1)
{
if(real->next->data==-1)
{
real=real->next;
continue;
}
else
{
tag++;
if(tag==3)
{
p=real->next;
real->next=real->next->next;
delete p;
tag=0;
number--;
continue;
}
real=real->next;
}
}
while(true)
{
if(real->data!=-1)
{
cout<<"最后一个人的数据为:"<<endl;
cout<<real->data<<endl;
break;
}
real=real->next;
}
}
void main()
{
LinkList real,real1;
int number;
cout<<"请输入有多少人"<<endl;
cin>>number;
real=creat_List(number);
deal(real,number);
}