// ConsoleApplication5.cpp : 此文件包含 “main” 函数。程序执行将在此处开始并结束。
//链表
//Josephus环问题
#include “pch.h”
#include
using namespace std;
struct Jonse
{
int code;
Jonse *next;
};
Jonse * create(int);
void showList(Jonse *);
void OutList(Jonse *, int,int);
int main() {
Jonse *head;
int num, val, beg;
cout << "\nplease input the number of the list: " << endl; cin >> num;
head = create(num);
cout << “开始位置” << endl; cin >> beg;
cout << “间隔” << endl; cin >> val;
showList(head);
OutList(head, beg, val);
}
Jonse * create(int m) {
Jonse *h, *p;
h = new Jonse;
p = h;
for (int i = 1; i <= m; i++) {
p->code = i;
if (i < m) {
p->next = new Jonse;
p = p->next;
}
}
p->next = h;
p = h;
return h;
}
void showList(Jonse * h) {
Jonse *p;
p = h;
do {
cout << p->code << endl;
p = p->next;
} while (p != h);
}
void OutList(Jonse * h, int i, int d) {//i 头,d间隔
Jonse *p, *q;
int k;
p = h;
//q是p的前驱指针,指向最后建立的结点
//当k=1时。q还是p的前驱,下面执行一次
for (q = h; q->next != h; q = q->next);
//当k>1时
for (k = 1; k < i; k++) {
q = p;
p = p->next;
}
//begin
while (p != p->next) {
for (k = 1; k < d; k++) {
q = p;
p = p->next;
}
cout << p->code << endl;
q->next = p->next;
delete p;
p = NULL;
p = q->next;
}
cout << “最后结点数字” << p->code << endl;
delete p;
p = NULL;
}