weixin_37736913 于 2017.09.18 15:27 提问

1个回答

yitian881112   2017.09.18 15:48

*/

#include

using namespace std;

struct MyNode

{

MyNode(int a_data):m_data(a_data),m_pNext(NULL) {}

int m_data;

MyNode *m_pNext;

};

class Josephus

{

public:

Josephus(int a_N, int a_K, int a_M):m_N(a_N),m_K(a_K),m_M(a_M)

{

createList();

outputList();

}

protected:

void createList();

void outputList();

private:

int m_N; //链表节点个数

int m_K; //第一个报数人的序号

int m_M; //报数出局的数

};

void Josephus::createList()

{

MyNode *pre = NULL;

MyNode *cur = NULL;

MyNode *p = new MyNode(1);

cur = p;

for (int i=2; i<=m_N; i++)

{

p = new MyNode(i);

pre = cur;

cur = p;

pre->m_pNext = cur;

}

int n=m_N;

while (n--)

{

cout << p->m_data << ",";

p = p->m_pNext;

}

cout << endl;

}

void Josephus::outputList()

{

MyNode *pre = NULL;

m_K;

while (m_K--) //寻找第K个人（开始报数的人）

{

pre = cur;

cur = cur->m_pNext;

}

while (m_N--) //输出链表中所有的节点值

{

int s = m_M-1;

while (s--) //寻找间隔M的人

{

pre = cur;

cur = cur->m_pNext;

}

MyNode *p = cur;

cout << p->m_data << ",";

cur = cur->m_pNext; //删除节点的过程

pre->m_pNext = cur;

delete p;

p=NULL;

}

}

int main()

{

Josephus josephus(100,5,5);

return 0;

}