约瑟夫环 代码
#include<iostream.h>
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data1;
int data2;
node *next;
}list;
list *creat(int n)//建立单循环链表
{
int x,y;
list *head,*tail,*p;
head=(list*)malloc(sizeof(list));
head->data1=1;
cout<<"输入第一个人的密码:";
cin>>x;
head->data2=x;
tail=head;
for(int i=1;i<n;i++)
{
int y;
cout<<"第"<<i+1<<"个人的密码:"<<endl;
cin>>y;
p=(list*)malloc(sizeof(list));
p->data1=i+1;
p->data2=y;
tail->next=p;
tail=p;
}
tail->next=head;
return head;
}
int main()
{
int n=0;
cout<<"指定初始报数上限值n:(n<=30)"<<endl;
cin>>n;
cout<<endl;
if(n>30)cout<<"输入有误,请重新输入:"<<endl;
while(n>30)cin>>n;
list *t,*pre,*q;
t=creat(n);//t指向第一个人
int m=6;
for(int j=0;j<n;j++)
{
for(int i=0;i<m-1;i++)
{
pre=t;t=t->next;
}
q=t;
m=t->data2;//取得出列人密码
cout<<"序号为"<<t->data1<<"的人出列"<<endl;
pre->next=t->next;
t=t->next;
delete(q);
}
return 0;
}