解决约瑟夫问题

来源:互联网 发布:java查询redis数据库 编辑:程序博客网 时间:2024/05/22 16:05

设有编号为123nn(n>0)个人围在一起,每人持有一个密码m,从第一个人开始报数,报到m时停止报数,报m的人出圈,再从下一个人开始重新报数,报到m时停止报数,报m的人出圈,……直到的所有人出圈为止。当给定nm后,输出出圈的次序。

※要求如下:自定义数据结构,确定存储方法,并设计算法。在主程序中输入nm后,输出结果。

源代码:

#include<iostream> 

using namespace std;
struct Node     
{
int data;
Node *next;
};
class T                       
{
public:
T(int x, int y);
void action();
private:
int n,m;
Node *first;
};
T::T(int x, int y)         
{
n = x;
m = y;
Node *p, *rear=NULL;
for (int i = 1; i <= n; i++)
{
p = new Node;
p->data = i;
if (i == 1)                        
{
first = p;
rear = p;
}
else
{
rear->next = p; 
rear = p;
}
}
rear->next = first;
}
void T::action()  
{
Node *p1, *p2=NULL, *p;
p1 = first;
for (int i = 1; i<n; i++)
{
int count = 1;
while (count++<m)
{
p2 = p1;
p1 = p1->next;
}
p = p1;
cout << p->data << " ";
p2->next = p1->next;
p1 = p1->next;
delete p;
}
cout << p1->data << endl;
}
int main()
{
int n, m;
cout << "人数:";
cin >> n;
cout << "密码m:";
cin >> m;
T test(n, m); 
cout << "约瑟夫环:";
test.action();
system("pause");
return 0;
}

调试结果:


0 0
原创粉丝点击