# 约瑟夫环

m的初始值为20；n=7，7个人的密码依次为：3，1，7，2，4，8，4，首先m值为6（正确的出列顺序为：6，1，4，7，2，3，5）。

// Child.h
struct Child {
int id;   // 编号
int passwd; // 密码
};
// Node.h
#include "Child.h"
struct Node {
Child* child;
Node* next;
};
#include "Node.h"
public:
void append(Child* child);
Child* remove(int index);
bool isEmpty();
private:
Node* rear; // 尾指针
int length;
};
rear = 0;
length = 0;
}
Node* n = new Node;
n->child = child;
if (!rear) n->next = n;
else {
n->next = rear->next;
rear->next = n;
}
rear = n;
++length;
}
Node* p = rear;
Node* f = 0;
for (int i = -1; i < index % length - 1; ++i)
p = p->next;
if (p->next == p) {
f = p;
rear = 0;
}
else {
f = p->next;
p->next = p->next->next;
if (p != rear)
rear = p;
}
Child* child = f->child;
delete f;
--length;
return child;
}
return rear == 0;
}
// main.cpp
#include <iostream>
int main() {
using namespace std;
cout << "Please input the password of each child by order:" << endl;
int id = 1;
int passwd;
while (cin >> passwd) {
Child* c = new Child();
c->id = id;
c->passwd = passwd;
l.append(c);
++id;
}
int m = 20;
while (!l.isEmpty()) {
Child* c = l.remove(m - 1);
id = c->id;
m = c->passwd;
delete c;
cout << id;
if (!l.isEmpty()) cout << ", ";
}
cout << endl;
return 0;
}

12-27 2961

10-03 5272

10-12 299

05-15 3.3万

#### 约瑟夫环的实现

2018年05月21日 2KB 下载

11-24 3832

10-07 3457

06-13 2042

02-03 3605

10-21 1094