约瑟夫问题-链表实现

来源:互联网 发布:java通过url上传文件 编辑:程序博客网 时间:2024/06/06 15:53

约瑟夫问题_百度百科 http://baike.baidu.com/link?url=EuXtXV4hPi1AtRdzY0vMPG1gQg1kt3uCS5g4Bfy_RzWXAnDwwjJkhxWdRfk2LPnkqubRBTb52CXEaUa5jbIRaK

#include<stdio.h>#include<stdlib.h>#include<malloc.h>#define RECURSION//Monkey Node definitiontypedef struct node{ int number;struct node *next;}node;//Josephus Problem#ifdef RECURSIONvoid king(struct node *list,int m){int i;struct node *pout=list;if(pout->next != pout)    {//one more monkeysfor(i=1; i<m; i++)pout=pout->next;for(list=pout; list->next != pout;) list=list->next;printf("%5d",pout->number);//show the monkey to be outlist->next = pout->next;//get out of listfree(pout);//free the nodeking(list->next,m);//RECURSION}else//the last one monkeyprintf("\nThe king is the monkey %d\n",list->number);}#elsevoid king(struct node *list,int m){int i;struct node *pout=NULL;for(pout=list;pout->next!= pout;pout=list->next){for(i=1; i<m; i++)pout=pout->next;for(list=pout; list->next != pout;) list=list->next;printf("%5d",pout->number);//show the monkey to be outlist->next = pout->next;//get out of listfree(pout);//free the node}//the last one monkeyprintf("\nThe king is the monkey %d\n",list->number);}#endif//generate the cycle list of n monkeys (n>=1)struct node* CreateCycle(int n){int i;struct node *head,*tail,*newnode;tail = head = (struct node*)malloc(sizeof(struct node));head->number = 1;head->next = head;for(i=2;i<=n;i++){newnode = (struct node*)malloc(sizeof(struct node));newnode->number = i;newnode->next = head;tail->next = newnode;tail=newnode;}return head;}int main(void){int total,out;struct node *list=NULL;// n monkeys in totaldo{printf("How many monkeys in total:");scanf("%d",&total);}while(total<1);//which monkey gets out each timedo{printf("Which monkey to be out:");scanf("%d",&out);}while(out<1);list = CreateCycle(total);printf("monkeys out in order:\n");king(list,out);return 0;}


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 苹果5s无法关机怎么办 三星手机白屏了怎么办 电脑能上qq打不开网页怎么办? 电脑打不开机怎么办黑屏 英雄杀连接不上怎么办 炫舞时登陆器卸下载失败怎么办 电视为什么会出现登录超时怎么办 登录app时提示请求超时怎么办 手机来短信断网怎么办 百度网络不给力怎么办 网络连接不给力怎么办 抖音网络不给力怎么办 玩lol老是掉线怎么办 无线网络连接有防火墙怎么办啊 千牛重新获取enc-k怎么办 为什么说不能获取对方信息怎么办 qq炫舞客户端被修改怎么办 win7玩穿越卡顿怎么办 玩dnf就蓝屏怎么办win7 平板玩fgo闪退怎么办 微信总是说空间不足怎么办 激活卡时遇到服务器错误怎么办 悦平台服务器错误是怎么办 手机银行提示登录服务器错误怎么办 qq漂流瓶封了怎么办 我的世界被冻结怎么办 qq里被屏蔽了怎么办 qq领手游礼包账号存在异常怎么办 笔记本电脑太卡怎么办最有效 华为平板电脑忘记开机密码怎么办 平板电脑忘记开机密码怎么办 平板电脑忘了开机密码怎么办 qq文件已被损坏怎么办 斗地主没痘了怎么办 熹妃q传金币不够用怎么办 苹果手机玩王者卡怎么办 苹果6玩王者荣耀卡怎么办 苹果macbook开不了机怎么办 苹果7震动像拖拉机一样怎么办 win10笔记本玩lol卡怎么办 苹果笔记本密码忘了怎么办