约瑟夫环自己以前写过,现在想用数据结构实现一次。
先贴上自己先前用数组实现的代码:
/*
约瑟夫环
有n个人(n<=1000),用1,2,...,n编号,顺序排列,并首尾相连围成一圈。
从第一个人开始报数(从1到4),凡报到4的人退出圈子,
且后面的人继续报数(同样从1到4报数),问最后留下的是原来第几号的那一位
输入人数输出最后剩下的人。
*/
#include<stdio.h>
int main()
{
int a[1001],i,j,k,n;
scanf("%d",&n);
for(i=1; i<=n; i++)
a[i]=i;
for(i=1,j=1,k=n; ;j++,i++)
{
if(k==1)break;
if(i>n)i-=n;
if(a[i]==0)
{
j--;continue;
}
if(j%4==0)
{
if(a[i]!=0)
{
a[i]=0; k--;
}
else
{
j--;continue;
}
}
}
for(i=1; i<=n; i++)
{
if(a[i]!=0)
{
printf("%d",a[i]);
break;
}
}
return 0;
}
下面是链表实现的约瑟夫环/*
53人从1-4开始报数,。。。(和前面雷同)
*/
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
int visited;
struct node* next;
}*linklist,list;
int length = 53;
linklist creat()
{
int number;
linklist temp,p;
linklist head;
head = (linklist)malloc(sizeof(list));
head->data =1;
head->visited = 0;
head->next = NULL;
temp = head;
for(number=2;number<=53;number++)
{
p = (linklist)malloc(sizeof(list));
p->data = number;
p->visited = 0;
p->next = temp->next;
temp->next = p;
temp = temp->next;
}
temp->next = head;
return head;
}
int work(linklist plist)
{
linklist head = plist;
linklist tmp = plist->next;
int i=4;
int flag=1;
while(length != 1)
{
if(head->visited){head = head->next;continue;}
if(flag == i && head->visited == 0)
{
length--;
head->visited = 1;
head = head->next;
flag=1;
}
if(head->visited){head = head->next;continue;}
head = head->next;
flag++;
}
if(plist->visited == 0){printf("%d\n",plist->data);return 1;}
while(tmp->data != plist->data)
{
tmp = tmp->next;
if(tmp->visited == 0){printf("%d\n",tmp->data);break;}
}
return 1;
}
int main()
{
linklist head = NULL;
head = creat();
work(head);
return 0;
}