#include<iostream>
using namespace std;
struct AP
{
int m;
int next;
int last;
};
class Joeph
{
public:
Joeph();
void Joephstart(int);
int Joephjudge();
void Joephshow();
private:
AP people[100];
int n;
int first;
int number;
int count;
int out[30];
};
Joeph::Joeph()
{
cout << "请输入参加人员和他们的密码" << endl;
cin >> n;
count = n;
int temp;
cin >> temp;
people[0].m = temp;
people[0].next = 1;
people[0].last = n - 1;
for (int i = 1; i < n - 1; i++)
{
cin >> temp;
people[i].m = temp;
people[i].next = i + 1;
people[i].last = i - 1;
}
cin >> temp;
people[n - 1].m = temp;
people[n - 1].next = 0;
people[n - 1].last = n - 2;
cout << "请输出初始密码" << endl;
cin >> first;
/*for (int i = 0; i <= 6; i++)
{
cout << people[i].next << endl;
cout << "1" << endl;
}*/
number = 0;
}
void Joeph::Joephstart(int a)
{
//cout << first << endl;
if (a == 1)
{
//cout << "1" << endl;
number = people[number].next;
}
for (int i = 1; i <= first; i++)
{
if (i == first)
{
if (Joephjudge())
{
//cout << "2" << endl;
Joephstart(1);
break;//当时没有进行处理
}
else
{
out[n - count] = people[number].next + 1;
return;
}
}
//cout << number << endl;//当前节点的number
number = people[number].next;//下一个节点的number
//cout << i << " " << number << endl;
}
return;
}
int Joeph::Joephjudge()
{
first = people[number].m;
int last = people[number].last;//当前节点
int next = people[number].next;
//cout << last << " " << next << endl;
people[last].next = next;
people[next].last = last;
out[n - count] = number + 1;
count--;
//cout << "count值为" << count << endl;
/*int ny=0;
for (int i = people[number].next; ny < count; i = people[i].next)
{
cout << "输出链表" << people[i].last << " " << i << " " << people[i].next << endl;
ny++;
}*/
//cout << first <<" "<<number << endl;//每一次调用完成后的number
if (count == 1) {
return 0;
}
else
return 1;
}
void Joeph::Joephshow()
{
for (int i = 0; i < n; i++)
{
cout << out[i] << endl;
}
}
int main()
{
Joeph a;
a.Joephstart(0);
a.Joephshow();
return 0;
}
此代码包括测试的部分,但也已用标注清楚。
特点:用类进行封装,通过结构体实现双向链表,实现节点的记录,通过类进行全部函数的处理。
最初犯得错误,我希望利用递归,实现每一次循环的处理,所以给函数设计了传参,本来这是可行的方案,但是我没有进行返回的处理,return之后我的函数会继续执行循环,而且是循环调用结束的时候已经完成了对所有数据的处理,所以需要跳出循环,返回上一级(最初的错误已经标注出)。
重要的是错误的形式,而并不是这种线性表的写法,这并不是理想的线性表写法。
return code;