实现约瑟夫环的算法
来源:互联网 发布:mac版windows系统下载 编辑:程序博客网 时间:2024/05/16 01:57
一)采用数组实现(适用于数字比较小):
#include <stdio.h>void josephus(const unsigned int nNum, const unsigned int nDistance, const unsigned int nBegin){if(nNum <= 0 || nDistance <= 0 || nBegin <= 0)return;int i, j, *nPassword = new int [nNum];for(i = 0;i < nNum;i ++){nPassword[i] = nDistance;//每个人的口令都相同的时候}int k = 0, iStart = nBegin;//此语句重要,第一个退出环的for(i = 0;i < nNum;i ++){j = 1;while(j < iStart){while(nPassword[k] == 0){k = (k + 1) % nNum;}j ++;k = (k + 1) % nNum;}while(nPassword[k] == 0){k = (k + 1) % nNum;}printf("%3d ",k + 1);iStart = nPassword[k];nPassword[k] = 0;}}void main(){josephus(100,3,1);}
二)采用链表实现(普遍适用):
//链表方法:#include <stdio.h> #include <malloc.h> struct node { int nNum,nPassword; struct node * next; }; typedef struct node * LNode; LNode CreateList(const int num,const int nPwd) { int i; LNode head = NULL,p = NULL,q = NULL; for(i = 1; i <= num; ++ i) { p = (LNode)malloc(sizeof(struct node)); p->nNum = i; p->nPassword = nPwd; if(NULL == head){head = p;}else{q->next = p;} q = p; } q->next = head; return q; } void josephus(const int num,const int nPwd,const int nBegin) { LNode q = CreateList(num,nPwd); LNode p = q->next; int iNum = num,iCall = nBegin; while(iNum --) { for(int i = 0; i < iCall - 1; ++ i) { q = p; p = p->next; } q->next = p->next; iCall = p->nPassword; printf("%3d ",p->nNum); free(p); p = q->next; } } void main() { josephus(100, 3, 1); }
//链表方法:#include <stdio.h> #include <malloc.h> struct node { int nNum,nPassword; struct node * next; }; typedef struct node * LNode; LNode CreateList(const int num,const int nPwd) { int i; LNode head = NULL,p = NULL,q = NULL; p = (LNode)malloc(sizeof(struct node)); p->nNum = 1; p->nPassword = nPwd; head = p; for(i = 2; i <= num; i ++) { q = (LNode)malloc(sizeof(struct node)); q->nNum = i; q->nPassword = nPwd; p->next = q; p = q; } q->next = head; return q; } void josephus(const int num,const int nPwd,const int nBegin) { LNode q = CreateList(num,nPwd); LNode p = q->next; int iNum = num,iCall = nBegin; while(iNum --) { for(int i = 0;i < iCall - 1; i ++) { q = p; p = p->next; } q->next = p->next; iCall = p->nPassword; printf("%3d\n",p->nNum); free(p); p = q->next; } } void main() { josephus(100,3,1); }
- 实现约瑟夫环的算法
- 约瑟夫环实现算法
- 小算法:约瑟夫环的Java实现
- 算法----约瑟夫环的简易实现
- 约瑟夫环的算法
- 约瑟夫(josephus)环算法实现
- 约瑟夫环的实现
- 约瑟夫环的实现
- 约瑟夫环的实现
- 约瑟夫环的实现
- 约瑟夫环的实现
- 约瑟夫环的实现
- 约瑟夫环的实现
- 约瑟夫环算法用面向对象的一种实现
- 一个约瑟夫环的算法
- 约瑟夫算法的C语言实现
- 约瑟夫环及其变种算法 java实现
- 简单数组实现约瑟夫环算法
- 原型模式学习资源
- Android TextView设置字体风格
- 当工作很纠结时,要么忍,要么狠,要么滚
- 判断本机是否安装office2003,2007和wps2007,2010
- ECP协议及在SX52BD与PC机间通信的实现
- 实现约瑟夫环的算法
- mac 系统相关常用网站 (驱动)
- UNREFERENCED_PARAMETER+的作用
- 服务器搭建技术——TortoiseHg配置具体过程
- 2012人人网校园招聘杭州站C++笔试题目
- 面向对象的三大基本特征
- 线程
- 用宏初始化结构体
- eclipse的android智能提示设置