您的位置:首页 > 其它

从面向结构到面向对象-----josephus问题(方法二:结构的应用)

2005-01-09 13:29 323 查看
今天看了一下josephus问题,突然有点想写些东西的冲动,结合自己的部份思想,于是便写了这几篇帖子。因为有几篇代码有点长,就分开发吧。如果对你有什么帮助的话,本人胜感欣慰。也许你会说,这个问题好多书上都有代码,但本人诣在于用不同的方法写出,让初学者体会一下从面向结构到面向对象的不同之处;同时你也可以看看我写的和一些书中的不同之处。如果你是个大虾,大可一笑了之,或赐教一番。

josephus问题:几个小孩围成一圈,从任意一个小孩间隔m顺时针方向数起,每数到第m个小孩时,该小孩就离开。最后一个剩下的就为胜利者。第几个为胜利者?

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//方法二:结构的应用
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include <iostream.h>
#include <iomanip.h>
struct jose
{
int code;
jose *next;
};
void mian()
{
int numOfBoys,interval;
cout<<"Please input the number of boys,"
<<endl
<<"interval of counting:";
cin>>numOfBoys>>interval;
jose *pJose=new jose[numOfBoys];
jose *pCurrent=pJose;
int itemsInLine=0;
for(int i=1;i<=numOfBoys;i++)
{
pCurrent->next=pJose+i%numOfBoys;
pCurrent->code=i;
pCurrent=pCurrent->next;
if(itemsInLine++%10==0)
cout<<endl;
cout<<setw(4)<<i;
}
itemsInLine=0;
int numOfCount;
cout<<"please input the number of count:"
<<endl;
while(1)
{
cin>>numOfCount;
if(0<numOfCount&&numOfCount<=numOfBoys)
break;
}
jose *pivot;
pCurrent=&pJose[numOfCount-1];
while(pCurrent->next!=pCurrent)
{
for(int j=0;j<interval;j++)
{
pivot=pCurrent;
pCurrent=pivot->next;
}
if(itemsInLine++%10==0)
cout<<endl;
cout<<setw(4)<<pCurrent->next;
pivot->next =pCurrent->next;
pCurrent=pivot;
}
cout<<endl
<<"the winner is:"
<<pCurrent->code
<<endl;
delete []pJose;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐