include
#include
struct people{
int number;
struct people *next;
};
void main()
{ int n;
int m;
int s;
cout<<"问题:设有N个人围成一圈,从第S个人开始进行1到M的报数\n数到M则出列,然后再从下一个人重新开始报数\n";
cout<<"数到M再出列,如此反复直到结束\n";
cout<<"下面请依次输入N,M,S\n";
cout<<"N=";
cin>>n;
for(;;){
cout<<"S=";
cin>>s;
if(s<=n)
break;
else
cout<<"对不起,S的输入非法,请重新输入!\n";//检验输入的有效性
}
cout<<"M=";
cin>>m;
people first;//表头
first.number=1;
people *now;//当前报数的人
people *pre;//前一个人
people *s_num;//第S个人的位置
people *head;//输出指针
people *outting;//输出变量
pre=&first;
cout<<"出列顺序为:\n";
s_num=&first;
for(int i=2;i<=n;i++){//建立长为N的循环链表
now=new people;
now->number=i;
pre->next=now;
pre= now;
now->next=&first;
if(i==s)//记录S的位置
s_num=now;
}
now=s_num;
pre=now;
for(i=1;inext;//寻找前一个人(防止M=1的输入)
for( i=1;i<=n;i++){
for(int j=1;jpre=now;
now=now->next;
}
if(i==1)//如果是第一个人,则记录他的位置,即重排后的链表头
{ head=now;
outting=now;
pre->next=now->next;
now=pre->next;
outting->next=NULL;
}
else//如不是,则依次建立新链表
{
pre->next=now->next;
outting->next=now;
outting=outting->next;
outting->next=NULL;
now=pre->next;
}
}
for(outting=head;outting!=NULL;outting=outting->next)//输出排序后的链表
cout<number<<' ';
}
Josephus No.2 链表实现 不保存输出
#include
#include
typedef struct Node
{
int num;
struct Node * next;
}person;
typedef person * position;
main()
{
int m,i,n,s,count=0;
position p,q,L;
clrscr();
L=(position)malloc(sizeof(person));
p=L;
printf("input the number of persons:\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
q=(position)malloc(sizeof(person));
q->num=i;
p->next=q;
q->next=NULL;
p=q;
}
p->next=L->next;
p=L;
printf("input the starting point:\n");
scanf("%d",&s);
printf("input the interval:\n");
scanf("%d",&m);
for(i=0;ip=p->next;
while(p->next!=p)
{
for(count=0;countp=p->next;
printf("%d ",p->next->num);
q=p->next;
p->next=p->next->next;
q->next=NULL;
free(q);
}
}
阅读(1332) | 评论(0) | 转发(0) |