约瑟夫问题 链表法
2015-07-13 20:25
190 查看
n代表总数,编号1~n,m代表从第几个开始数,k代表数几个就去掉
#include <iostream> #include <string> #include <cstring> #include <queue> #include <stack> #include <cmath> #include <algorithm> #include <cstdio> using namespace std; struct node { int num; node *next; node *per; }; void creat(node *head ,int n) { node *cur; cur = head; for(int i = 2 ;i <= n ; i ++ ) { node *temp = new node(); temp -> num = i; cur -> next = temp; temp -> per = cur; cur = temp; } cur -> next =head; head -> per = cur; } void john(node *head , int m ,int n ,int k) { int num = 1; node *cur = head; for(int i = 1 ; i < m ; i ++ ) { cur = cur -> next ; } int sum = 0; for(int i = 0 ; ; i ++ ) { if(num == k) { cout <<cur -> num <<endl ; cur -> per -> next = cur -> next; cur -> next -> per = cur -> per; sum ++ ; if(sum == n-1) { cur = cur-> next; break; } num = 0; } cur = cur -> next ; num ++ ; } cout << cur->num <<endl; } int main() { int n , m , k ; while(cin >> n >> m >> k) { node *head; head = new node(); head->num = 1; creat(head , n); john(head , m , n ,k); } }
相关文章推荐
- C#控制定位Word光标移动到任意行或者最后一行,取得光标位置等操作
- iOS 本地加载js文件
- [LeetCode] Factorial Trailing Zeroes
- Find Minimum in Rotated Sorted Array
- jQuery插件开发之boxScroll与marquee
- Android 开源框架ImageLoader基本介绍及使用
- 单源最短路径——Bellman--Ford算法
- const形参的函数重载
- easyui中datagrid和layout的问题
- DataTable数据转换为实体
- 介绍Google App Engine
- leetcode 027 —— Remove Element
- Node:普通归并
- 英格兰、威尔士、北爱尔兰教育体系
- 使用const关键字进行函数重载
- POJ 2886 Who Gets the Most Candies?(线段树·约瑟夫环)
- 第一篇博客
- POJ 2481 Cows
- Gym 100496A Avangard Latin Squares(矩阵游戏)
- JSP 标准标签库(JSTL)之最常用的JSTL标签总结