当前位置: 代码迷 >> C语言 >> [求助]各位高手好,请教一个有关链表的问题
  详细解决方案

[求助]各位高手好,请教一个有关链表的问题

热度:155   发布时间:2004-12-08 20:17:00.0
[求助]各位高手好,请教一个有关链表的问题

之前用数组解决过这样一个问题:

有一件礼物,要送给如下游戏的幸运者:有n个人围成一圈,从第一个人开始从1报数,报到m的人退出圈子,退出者的下一位开始从1重新报数,报到m的人退出圈子......直到最后一个人从圈子里面出来,最后走出来的人即为幸运者。编写程序,打印出来幸运者的编号,并打印各个人出圈的先后顺序。

现在要用链表来解决。用循环链表。我对链表非常不熟。解决不了。希望高手不吝赐教。非常感谢!!

搜索更多相关的解决方案: 链表  

----------------解决方案--------------------------------------------------------

#include <stdio.h> #include <malloc.h>

struct strNum { int num; struct strNum * pNext; };

void main() { int n=0,m=0; struct strNum *head,*p,*temp;

printf("Input the Number:"); scanf("%d",&n); if(n<2) { printf("Input Erro ! The Number is must >=2 .\n"); return; } printf("Input the m:"); scanf("%d",&m); if(m<2) { printf("Input Erro ! The m is must >=2 .\n"); return; }

p=head=(struct strNum *)malloc(sizeof(struct strNum)); p->pNext=head; p->num=1; for(;n>1;n--) { p->pNext=(struct strNum *)malloc(sizeof(struct strNum)); p->pNext->num=p->num+1; p=p->pNext; } p->pNext=head; n=1,p=head; for(;;) { n++; if(n%m==0) { n=0; if(p->pNext==p) { printf("The number is:%d",p->num); free(p->pNext); break; } else { temp=p->pNext; p->pNext=p->pNext->pNext; free(temp); } } p=p->pNext; } printf("\n"); }

看看能不能用!


----------------解决方案--------------------------------------------------------

不就是个 约 瑟夫问题吗??


----------------解决方案--------------------------------------------------------
多谢斑竹,急公好义的好人感激不尽!初次登陆论坛,没想到大家这么热心。以后还请大家多多帮助,谢谢。
----------------解决方案--------------------------------------------------------
高,实在是高
----------------解决方案--------------------------------------------------------
  相关解决方案