//有n个人围坐在一个圆桌周围,现从第s个人开始报数,数到第m
//的人出列,然后从出列的下一个人重新开始报数,数到第m的人
//又出列,…,如此反复直到所有的人全部出列为止。
#include <iostream>
#include <iomanip>
using namespace std;
typedef struct LNode{
int NO;
struct LNode * next;
}Lnode, *Josephus;
Josephus InitJosephus()
{
LNode * head = new LNode;
head->next = head;
head->NO = 0;
return head;
}
Josephus CreateJosephus(int enjoyIn)
{
LNode * node = NULL;
LNode * head = InitJosephus();
LNode * forword = head;
for( int i = 1; i <= enjoyIn; i++ )
{
node = new LNode;
node->NO = i;
forword->next = node;
forword = forword->next;
node->next = NULL;
}
forword->next = head->next;
return head;
}
void JoseProcess( Josephus &Jose, int position, int cycle)
{
Josephus p = Jose->next;
Josephus qTemp = NULL;
int temp;
for(int i = 0; i < position-1; i++ )
{
p = p->next;
}
cout<<"Out of the queue... "<<endl;
if(cycle == 1 && p->next != p)
{
qTemp = p;
while( qTemp->next != p )
qTemp = qTemp->next;
}
if(cycle == 1 && p->next == p)
{
cout<<"The winner is "<< p->NO <<" child! "<<endl;
}
while( p->next != p )
{
for(int j = 1; j < cycle; j++ )
{
qTemp = p;
p = p->next;
}
temp = p->NO;
qTemp->next = p->next;
delete p;
p = qTemp->next;
cout<<temp<<endl;
}
cout<<"The winner is "<< p->NO <<" child! "<<endl;
}
void main()
{
int enjoyIn;
int position;
int cycle;
cout<<"the total of the children : ";
cin>>enjoyIn;
cout<<endl<<"the position you want to access : ";
cin>>position;
cout<<endl<<"the cycle you want : ";
cin>>cycle;
cout<<endl;
Josephus Jose = CreateJosephus( enjoyIn );
JoseProcess( Jose, position, cycle);
}
本文介绍了一个经典的约瑟夫环问题,并通过C++代码详细展示了如何创建一个单链表来模拟这一问题的过程,最终找到最后一个留在圈中的人。
3301

被折叠的 条评论
为什么被折叠?



