约瑟夫环
#include<iostream>
#include<malloc.h>
using namespace std;
struct node
{
int no;
int code;
node *next;
};
int main()
{
int m, n, i, j;
node *p, *q, *first;
cout << "请输入m的值:";
cin >> m;
cout << "请输入人数 n:";
cin >> n;
for (i = 1; i <= n; i++)
{
if (i == 1)
{
first = p = (node*)malloc(sizeof(node));
if (p == 0)
return 0;
}
else
{
q = (node*)malloc(sizeof(node));
if (q == 0)
return 0;
p->next = q;
p = q;
}
cout << "请输入第 " << i << " 个人的密码: ";
cin >> (p->code);
p->no = i;
}
p->next = first;
p = first;
cout << "出列顺序为: ";
for (j = 1; j <= n; j++)
{
for (i = 1; i < m; i++, p = p->next);
m = p->code;
cout << p->no << " ";
p->no = p->next->no;
p->code = p->next->code;
q = p->next;
p->next = p->next->next;
free(q);
}
cout << endl;
return 0;
}