#include <iostream>
class Josephus
{
private:
unsigned int m_numberOfPeoples;
unsigned int m_killedNumber;
class People
{
public:
unsigned int m_number;
People* m_pNextPeople;
People(unsigned int i):m_number(i),m_pNextPeople(NULL){}
};
People* m_pHeadJosephus;
public:
Josephus(unsigned int number,unsigned int killedNumber):m_numberOfPeoples(number),
m_killedNumber(killedNumber),m_pHeadJosephus(NULL)
{
if( m_numberOfPeoples < 2 )
{
m_pHeadJosephus = new People(1);
m_pHeadJosephus->m_pNextPeople = m_pHeadJosephus;
}
else
{
m_pHeadJosephus = new People(1);
People* pTempPeople = m_pHeadJosephus;
unsigned int addPeopleNumber = 2;
while( addPeopleNumber <= m_numberOfPeoples )
{
pTempPeople->m_pNextPeople = new People(addPeopleNumber);
addPeopleNumber++;
pTempPeople = pTempPeople->m_pNextPeople;
}
pTempPeople->m_pNextPeople = m_pHeadJosephus;
}
}
void printJosephus() const;
void killPeople();
void StartNumber(unsigned int start);
};
void Josephus::printJosephus() const
{
People* pTempPeople = m_pHeadJosephus;
std::cout << "\t\t";
while(m_pHeadJosephus != pTempPeople->m_pNextPeople)
{
std::cout << pTempPeople->m_number << "->";
pTempPeople = pTempPeople->m_pNextPeople;
}
std::cout << pTempPeople->m_number << std::endl;
}
void Josephus::killPeople()
{
People* pTempPeople = m_pHeadJosephus;
while(m_pHeadJosephus != m_pHeadJosephus->m_pNextPeople)
{
printJosephus();
unsigned int increase = 1;
for (; increase < m_killedNumber; increase++)
{
pTempPeople = pTempPeople->m_pNextPeople;
}
People* pPeople = pTempPeople->m_pNextPeople;
if (m_pHeadJosephus == pPeople)
{
m_pHeadJosephus = pPeople->m_pNextPeople;
}
std::cout << "kill person " << pTempPeople->m_number << std::endl;
*pTempPeople = *pPeople;
delete pPeople;
}
std::cout<< "Last alive people:\n";
printJosephus();
}
void Josephus::StartNumber(unsigned int start)
{
unsigned int startNumber = 1;
People* ptempPeople = m_pHeadJosephus;
while( startNumber != start )
{
ptempPeople = ptempPeople->m_pNextPeople;
startNumber++;
}
m_pHeadJosephus = ptempPeople;
}
int main(){
Josephus j(10, 2);
j.StartNumber(2);
j.killPeople();
return 0;
}
![这里写图片描述](https://img-blog.csdn.net/20170717150753549?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGlhb2xpeGkxOTkzMTE=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)