......
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
}LinkList;
......
//-------------------------------------------------------------------------------------
int main(void)
{
int n,s,m;
LinkList *sa = NULL;
printf("\t<<<<<约瑟夫问题求解>>>>>\n输入人数:"); scanf("%d",&n);
printf("从第几个人开始报数:"); scanf("%d",&s);
printf("到第几个人则出列:"); scanf("%d",&m);
sa = Joseph(n,s,m);
printf("按如下顺序出列:\n");
Disp(sa);
Free(sa);
return 0;
}
//-------------------------------------------------------------------------------------
LinkList *Creat_L(int n){
int i;
LinkList *L,*p,*s = NULL;
if(!(p = L = (LinkList *)malloc(sizeof(LinkList))))
{printf("\n\tOut of Memory!\n"); return 0;}
L->next = NULL;
if(!(s = (LinkList *)malloc(sizeof(LinkList))))
{printf("\n\tOut of Memory!\n"); return 0;}
for(i = 1;i <= n;i++)
{
s->data = i;
s->next = NULL;
p->next = s;
p = s;
if(!(s = (LinkList *)malloc(sizeof(LinkList))))
{printf("\n\tOut of Memory!\n"); return 0;}
}
return L;
}
//-------------------------------------------------------------------------
LinkList *Joseph(int n,int s,int m) //建立n个结点的单链表,从s报数,到第m人则出列;
{
if(s<1 || m<1) {printf("输入有错!\n");exit (0);}
LinkList *L = Creat_L(n);
printf("\n\n\n解决约瑟夫问题,有 %d 个人坐在圆桌周围,示意如下:\n",n);
Disp(L); printf("\n\n从第 %d 个人开始报数,数到 %d 的人出列。",s,m);
int count = 1; //count计数器;
LinkList *new_p,*q,*p = NULL;
new_p = q = L->next;
while(new_p->next) //先用new_p链到L->next,循环链表?
{
new_p = new_p->next;
if(++count < s) q = q->next; //找到第s-1结点;
}
new_p->next = L->next;  
作者在 2006-09-11 08:51:00 发布以下内容