约瑟夫问题循环链表解法、队列解法
2015-07-24 21:12
423 查看
(1)单链表解法:
(2)队列解法(利用FIFO特性)
typedef struct node{ //定义单链表结构,next指向下一个节点 int key; node *next; }node,*pnode; void test(){ int n,m; cout<<"number of people per circle n = "; cin>>n; cout<<"the m'th person to be killed m = "; cin>>m; cout<<"the kill list is: "; pnode ptr = (pnode)malloc(sizeof(node)*n); //分配内存 pnode p = ptr; //p为头指针head for(int i = 0; i < n-1; i++){ //对指针赋值 ptr->key = i+1; ptr->next = ptr+1; ptr = ptr->next; } ptr->key = n; //最后一个指针赋值为n ptr->next = p; //最后一个指针指向head p while(p != p->next){ //当循环链表不为空,即next不指向自身 for(int i = 0; i < m-2; i++) //数到第m-1个人 p = p->next; cout<<p->next->key<<" "; //输出第m个人 p->next = p->next->next; //将第m-1的next指向第m+1个人,即删除第m个人 p = p->next; //p从下一个人重新计数 } cout<<p->key<<endl; }
(2)队列解法(利用FIFO特性)
void test2(){ queue<int> circle; //FIFO int n = 12, m = 7; for(int i = 0; i < n; i++) circle.push(i+1); while(circle.size() != 0){ for(int i = 0; i < m-1; i++){ //第m个人将被移除队列circle int temp = circle.front(); circle.pop(); circle.push(temp); } cout<<circle.front()<<" "; circle.pop(); } }
相关文章推荐
- 梅的体重问题
- BZOJ 3446: [Usaco2014 Feb]Cow Decathlon( 状压dp )
- Doing Homework(HDU 1074状压dp)
- linux 之makefile语法学习1
- Nginx上传文件提示413 Request Entity Too Large
- 物联网产品:你需要知道的9种智能家居产品
- Show html in WebGl
- C++Premer Plus学习(五)——函数探幽
- 南阳oj 语言入门 房间安排
- 南阳 oj 语言入门 A Famous Music Composer
- HDU 1163 Eddy's digital Roots(九余数定理+快速幂)
- HDU 2852 KiKi's K-Number(线段树单点更新)
- Linux SSH 免密码登录
- 烦躁的一天
- hdu 3118 Arbiter(枚举构造二分图)
- C++之贪吃蛇
- 2015 HUAS Summer Training#2 E
- netBeans调试时不进入java内部类(jdk源码)的方法
- 没有任何关闭socket的日志,客户端和服务端进程都在, 网络连接完好, 为什么进行某操作后好好的tcp连接莫名其妙地断了呢?
- java.util.Random.nextInt(int n)方法实例