|
5鱼币
/*********************************
对应教材2.7.1节,约瑟夫环问题
**********************************/
#include<iostream>
using namespace std;
struct Node
{
int data;
struct Node* next;
};
class JosephRing
{
public:
JosephRing();
JosephRing(int n);
~JosephRing();
void Joseph(int m);
private:
Node* rear;
};
JosephRing::JosephRing()
{
rear = NULL;
}
JosephRing::JosephRing(int n)
{
Node* s = NULL;
rear = new Node;
rear->data = 1; rear->next = rear;
for (int i = 2; i <= n; i++)
{
s = new Node; s->data = i;
s->next = rear->next;
rear->next = s;
rear = s;
}
}
JosephRing :: ~JosephRing()
{
if (rear != NULL) {
Node* p = rear->next;
while (rear->next != rear)
{
rear->next = p->next;
delete p;
p = rear->next;
}
delete rear;
}
}
void JosephRing::JosephRing(int m)(错误:不能在构造函数上指定函数类型)
{
Node* pre = rear, * p = rear->next;
int count = 1;
cout << "出环顺序是:";
while (p->next != p)
{
if (count < m) {
pre = p; p = p->next;
count++;
}
else{
cout << p->data << "\t";
pre->next = p->next;
delete p;
p = pre->next;
count = 1;
}
}
cout << p->data << "\t";
delete p;
rear = NULL;
}
int main()
{
int n, m;
cout << "请输入约瑟夫环的长度是:";
cin >> n;
cout << "请输入密码";
cin >> m;
JosephRing R(n);
R.Joseph(m);
return 0;
}
本帖最后由 sunrise085 于 2020-9-26 15:36 编辑
第25行是构造函数,无返回值。
第52行,你把函数名写错了,把Joseph写成JosephRing了。前者是一般函数,后者是构造函数。
呃,请不要重复发帖。
- #include<iostream>
- using namespace std;
- struct Node
- {
- int data;
- struct Node* next;
- };
- class JosephRing
- {
- public:
- JosephRing();
- JosephRing(int n);
- ~JosephRing();
- void Joseph(int m);
- private:
- Node* rear;
- };
- JosephRing::JosephRing()
- {
- rear = NULL;
- }
- JosephRing::JosephRing(int n)
- {
- Node* s = NULL;
- rear = new Node;
- rear->data = 1; rear->next = rear;
- for (int i = 2; i <= n; i++)
- {
- s = new Node; s->data = i;
- s->next = rear->next;
- rear->next = s;
- rear = s;
- }
- }
- JosephRing :: ~JosephRing()
- {
- if (rear != NULL) {
- Node* p = rear->next;
- while (rear->next != rear)
- {
- rear->next = p->next;
- delete p;
- p = rear->next;
- }
- delete rear;
- }
- }
- void JosephRing::Joseph(int m)//你把函数名写错了,把Joseph写成JosephRing了。前者是一般函数,后者是构造函数
- {
- Node* pre = rear, * p = rear->next;
- int count = 1;
- cout << "出环顺序是:";
- while (p->next != p)
- {
- if (count < m) {
- pre = p; p = p->next;
- count++;
- }
- else{
- cout << p->data << "\t";
- pre->next = p->next;
- delete p;
- p = pre->next;
- count = 1;
- }
- }
- cout << p->data << "\t";
- delete p;
- rear = NULL;
- }
- int main()
- {
- int n, m;
- cout << "请输入约瑟夫环的长度是:";
- cin >> n;
- cout << "请输入密码";
- cin >> m;
- JosephRing R(n);
- R.Joseph(m);
- return 0;
- }
复制代码
|
最佳答案
查看完整内容
第25行是构造函数,无返回值。
第52行,你把函数名写错了,把Joseph写成JosephRing了。前者是一般函数,后者是构造函数。
呃,请不要重复发帖。
|