您的位置:首页 > 其它

约瑟夫问题 链表法

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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: