#include <stdio.h>
#include <stdlib.h>
typedef struct cerclelink
{
int num;
struct cerclelink *next;
}Node,*pNode;
pNode create(int );
int Joseph(pNode,int);
int main()
{
int n,k;
printf("enter number of children: ");
scanf("%d",&n);
printf("enter the number which use to circle :");
scanf("%d",&k);
pNode head=create(n);
printf("\nthe quence of out of list is :\n");
/*调用约瑟夫游戏函数进行计算,之所以要k-1是因为指针/
要放在将要删除的那个元素的前一个元素上面*/
printf("the last children is :%d\n",Joseph(head,k-1));
return 0;
}
pNode create(int n)
{
pNode head,p,q;
head=(pNode)malloc(sizeof(Node));/*为头节点分配内存*/
head->num=1;/*先为头节点赋值1*/
p=head;
int i;
for(i=2;i<=n;i++)
{
q=(pNode)malloc(sizeof(Node));
q->num=i;
p->next=q;
p=q;
p->next=head;/*每次都将最后一个节点指向头节点*/
}
return head;
}
int Joseph(pNode head ,int k)
{
int count=1;
pNode p=head,q=head,t=NULL;
if(k==0)/*如果每次都只查到1,那就相当于顺序出列了*/
{
while(p->next!=head)
p=p->next;
return p->num;
}
else
{
while(p->next!=p)
{
while(count!=k)
{
p=q=q->next;
count++;
}
count=1;
q=q->next->next;
t=p->next;
p->next=q;
p=q;
printf("\n***%d***\n",t->num);
free(t);
}
return p->num;
}
}
约瑟夫环问题
最新推荐文章于 2022-05-04 19:46:17 发布
