#include
#include
#include
#include "conio.h"
#include
#include
/*
Joseph 一个约瑟夫问题求解,高手请进!!!
编号为1,2,3...n的n个人围成一圈,从编号为k的人开始报数,
报到m的人出列,再从出列的下一个人开始报数,报到m的人又
出列,直到所有人都出列,求这n个人的出列顺序.
用C语言编写算法,将结果以顺序表和单链表输出
*/
typedef struct per
{
long n;
struct per *next;
} s;
s *createcircle(s **head)
{
s *p=*head,*tail;
long i,sum;
printf("Input the sum :\n");
scanf("%ld",&sum);
for(i=1;i<=sum;i++)
{
p=(s*)malloc(sizeof(s));
p->n=i;
p->next=NULL;
if(*head==NULL)
{
*head=p;
tail=p;
}
else
{
tail->next=p;
tail=p;
}
}
tail->next=*head;
return tail;
}
void countcircle(s *head,s *tail)
{
long i,len;
s *p=head,*p2;
printf("Input the increment:\n");
scanf("%ld",&len);
printf("Input the start:\n");
scanf("%d",&i);
p2=tail;
while(p->n!=i)
{
p2=p;
p=p->next;
}
i=1;
while(p!=p->next)
{
if(i%len==0)
{
printf("%6ld\n",p->n);
p2->next=p->next;
free (p);
p=p2->next;
}
else
{
p2=p;
p=p->next;
}
i++;
}
printf("The number the remaining person is:%ld\n",p->n);
}
void main ()
{
s *head=NULL,*tail;
tail=createcircle(&head);
countcircle(head,tail);
system("pause");
}
阅读(595) | 评论(0) | 转发(0) |