您的位置:首页 > 编程语言

“约瑟夫问题”实现代码加运行截图(ADT小组)

2014-09-30 00:31 381 查看
#include<iostream>
struct people
{
int m;
people* next;
};

class game
{
public:
game(int, int);//构造函数
void count(int);//计数函数
void Delete();//删除函数
void judgement();//裁判操作函数
private:
people *p, *frist = NULL;//头指针,与当前位置指针
int lenght = 0;
};
game::game(int n, int m)
{
frist = new people;
frist->m = m + 1;//给头结点赋予标识值
frist->next = NULL;
people * s, *r;
s = frist;
r = NULL;
for (int i = 0; i < n; i++)//动态内存分配
{
r = new people;
r->m = m;
s->next = r;
r->next = NULL;
s = r;
lenght += 1;
}
r->next = frist;
p = frist;

}
void game::count(int m)
{
for (int i = 0; i < (m - 2);)//这里的位置指针只移动到删除位置的前一位
{
if (p->m == m + 1)//为了跳过头结点的操作
{
p = p->next;
}
else
{
p = p->next;
i++;
}
}
}
void game::Delete()//删除
{
people *s;
s = p->next;
p->next = s->next;
delete s;
lenght -= 1;
}
void game::judgement()//裁判操作
{
for (; 1 == 1;)
{
count(frist->next->m);//开始计数
Delete();//删除
if (lenght == 1)//判断是否只剩一个人
{
break;
}
}//重新计数
using std::cout;
using std::endl;
cout << "优胜者已经产生" << endl;
}
int main()
{
int n, m;
using std::cout;
using std::endl;
cout << "请输入人数n,与密码m" << endl;
using std::cin;
cin >> n >> m;
game s(n, m);
s.judgement();
system("pause");
return 0;
}

运行截图(比赛进行中):



运行截图(比赛结束):

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: