背景
约瑟夫环(约瑟夫问题)是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。
数组实现
#include<stdio.h>
#define N 5
#define total 100
int main()
{
int a[total]={0};
int add=0;
int human=total;
for(int i=0;i<total;i++)
{
if(a[i]!=-1)
add++;
if(add==N)
{
a[i]=-1;
human--;
add=0;
if(human==0)
{
human=i;
break;
}
}
if(i==total-1)
i=-1;
}
printf("the last one:%d",human);
return 0;
}
链表实现:
#include<stdio.h>
#define TOTAL 100
#define COUNT 5
struct node
{
int num;
node* next;
}*head;
node* createman()
{
node* p=new node;
p->next=NULL;
return p;
}
node* sitaround()
{
head=createman();
node* father=head;
father->num=1;
for(int i=2;i<=TOTAL;i++)
{
father->next=createman();
father->next->num=i;
father=father->next;
}
father->next=head;
return head;
}
void outman(node* father)
{
node* p=father->next->next;
delete(father->next);
father->next=p;
}
int main()
{
head=sitaround();
node* surviver=head;
while(surviver->next!=surviver)//就剩一个人,自己的下一个指向自己
{
for(int i=1;i<COUNT-1;i++)//surviver初始值数1,所以从1开始;因为outman函数直接删掉下一个人,所以不能让count-1执行
surviver=surviver->next;
outman(surviver);//数到COUNT的人不出声了直接拍死
surviver=surviver->next;//阵亡的人后面的人开始数数
}
printf("surviver is : No.%d",surviver->num);
return 0;
}
约瑟夫环属于挺简单的一个问题,不多做说明。
如果实现从第k个人开始数数,改变初始起点即可。
本文最有价值的还是环装链表的实现