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

今天看了一下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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值