约瑟夫环
【问题描述】
约瑟夫环问题的一种描述是:编号为1,2,......,n的n个人按顺时针的方向围坐一圈,每个人持有一个密码(正整数)。一开始任选一个正整数作为报数的上限值m,从第一个人开始按顺时针方向自1开始顺序报数,报到m时停止报数。报m的人出列,将他的密码作为新的m值,从他的顺时针方向上的下一个人开始重新报数,如此下去,直至所有人全部出列为止。试设计一个程序求出出列顺序。
【程序实现】
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
int m, n;
struct josephstruct
{
int id;
int mm; /*密码*/
struct josephstruct *pre; /*前驱节点*/
struct josephstruct *next; /*后继节点*/
};
struct josephstruct *head;
void joseph()
{
struct josephstruct *p;
int count = n;
int tempm = m - 1;
p = head;
while (count != 0)
{
if (tempm == 0)
{
printf("%d ", p->id);
tempm = p->mm - 1;
p->next->pre = p->pre;
p->pre->next = p->next;
p = p->next;
count--;
}
else
{
p = p->next;
tempm--;
}
}
}
int main()
{
struct josephstruct *temp;
printf("输入报数上限值: ");
scanf("%d", &m);
printf("输入约瑟夫环大小(输入0退出): ");
while (scanf("%d", &n) != EOF)
{
if (n == 0)
break;
printf("输入%d个人的密码: ", n);
for (int i = 0; i < n; i++)
{
struct josephstruct *p;
p = (struct josephstruct *)malloc(sizeof(struct josephstruct));
if (i == 0)
{
p->next = p;
p->pre = p;
head = p;
}
else
{
p->next = head;
head->pre = p;
temp->next = p;
p->pre = temp;
}
temp = p;
p->id = i + 1;
scanf("%d", &p->mm);
}
printf("输入初始报数值: ");
scanf("%d", &m);
printf("淘汰序列: ");
joseph();
printf("\n输入约瑟夫环大小(输入0退出): ");
}
return 0;
}
该程序中主要采用双循环链表(单循环链表更加简便,这里主要是用于练习相关知识所以采用双循环链表),在这里只设置头结点,通过对于结点的删除以及添加来实现该程序。