数据结构课设,最简单的约瑟夫环
/*
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
实验题1.2 问题描述:
编号为1,2,···,n的n个人围坐在一圆桌旁,每人持有一个正整数的密码。
从第一个人开始报数,报到一个预先约定的正整数m时,停止报数,报m的人退席,
下一个人又重新从1开始报数,依此重复,直至所有的人都退席。
编一程序输出他们退席的编号序列。
例如,设m=20,n=7,7个人的密码依次是3,1,7,2,4,8,4,
则退席的人的编号依次为6,1,4,7,2,3,5。
提示2:
用不带表头结点的循环单链表表示围成圆圈的n个人;
建立此循环单链表;
某人离席相当于删除一个结点要正确设置程序中循环终止的条件和删除结点时指针的修改变化。
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
the example for joseph:
example input:
20 7
3 1 7 2 4 8 4
example output:
6 1 4 7 2 3 5
*/
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<malloc.h>
using namespace std;
typedef struct node{
int num, pas, peo;
node *pre, *next;
}cLinkList, *Lnode;
void CreateTree( Lnode &Tree, int n ){
Lnode temp, p;
int t;
p = new cLinkList;
p -> next = NULL;
Tree = p;
Tree -> peo = n;
for( int i = 1; i <= n; ++i ){
temp = new cLinkList;
// temp = ( Lnode )malloc( sizeof( cLinkList ) );
cin >> t;
temp -> num = i;
temp -> pas = t;
temp -> next = p -> next;
p -> next = temp;
p = p -> next;
}
p -> next = Tree -> next;
}
void Print( Lnode &Tree, int n ){
Lnode p, temp;
p = new cLinkList;
p = Tree -> next;
while( n-- ){
cout << p -> num << " " << p -> pas << endl;
p = p -> next;
}
}
void Joahson( Lnode &Tree, int m ){
Lnode p, temp;
p = new cLinkList;
p = Tree -> next;
// the Tree -> peo is the sum of peoples;
while( Tree -> peo != 1 ){
int i;
for( i = 1; i < m; ++i ){
//control the reserach the before the people of goal
if( i != m- 1 )
{
p = p -> next;
}
}
cout << p -> next -> num << " ";
// the next m is the password add the one
m = p -> next -> pas + 1;
p -> next = p -> next -> next;
Tree -> peo--;
}
cout << p -> num << endl;
}
int main(){
int m, n;
//create the tree
Lnode str;
//the people's number ans the password
cin >> m >> n;
//create the tree
CreateTree( str, n );
//the useful
Joahson( str, m );
//Print( str, n );
}