首先指定一个数为第几个人死,然后报数,到这个人死的时候他可以重新指定新从他后面开始的第几个人死,循环下去
#include<iostream>
using namespace std;
#include<ctime>
//循环链表
//动态约瑟夫问题,cur中储存下一次第几个人死
//创建结构体
typedef struct Pnode
{
int data;
int cur;
Pnode *next;
}*linklist;
void creatlist(linklist &L, int n)
{
linklist head, temp;
head = (linklist)malloc(sizeof(Pnode));//创建头指针
head->next = L;
int i = 1;
if (n > 0)
{
L->data =i;
L->cur = rand() % 10+1;
L->next = NULL;//给第一个结点赋值
temp = L;
for ( i = 1; i < n; i++)
{
linklist p = (linklist)malloc(sizeof(Pnode));
p->data =i+1;
p->cur = rand() % 10+1;
temp->next = p;
p->next = NULL;
temp = p;
}
temp->next = L;//尾结点指向头结点
free(head);//释放head
}
else
{
cout << "error to input" << endl;
}
}
void print(linklist &L,int n)
{
linklist p=L,k=L;
cout << "data" << endl;
for (int i = 0; i < n; i++)
{
cout <<p->data << " ";
p = p->next;
}
cout << endl;
cout << "cur" << endl;
for (int i = 0; i < n; i++)
{
cout << k->cur << " ";
k = k->next;
}
cout << endl;
}
//在第n个位置插入元素e
void insertlist(linklist &L, int n, int e)
{
linklist k=L,temp;
for (int i = 1; i < n-1; i++)
{
k = k->next;
}
linklist p = (linklist)malloc(sizeof(Pnode));
p->data = e;
temp = k->next;
k->next = p;
p->next = temp;
}
int main()
{
srand((unsigned int)time(NULL));
linklist L=(linklist)malloc(sizeof(Pnode));
creatlist(L, 41);
print(L, 41);
int i = 1,num=0;
cin >> num;//第一次循环让第一个人死
while (L->next!=L)
{
L = L->next;
++i;
if (i % num == num-1)
{
linklist temp;
temp = L->next;
num = temp->cur;//把死亡结点的cur赋值给num
L->next = temp->next;
cout << temp->data << "->";
free(temp);//释放该元素
L=L->next;
i = 1;//重置数目,因为每次释放的结点数不一样,无法统一取整
}
}
cout << endl;
system("pause");
return 0;
}