约瑟夫环 数据结构实验
一.问题描述:约瑟夫问题的一种描述为,编号为1,2,3,……n的n个人按顺时针方向围坐一圈,每人持有一个密码(正整数)。一开始任选一个正整数作为报数上限值m,从第一个人开始按顺时针方向自1开始顺序报数,报到m时停止报数。报m的人出列,将他的密码作为新的m的值,从他在顺时针方向上的下一个人开始重新从1报数,如此下去,直至所有的人全部出列为止。试设计一个程序求出出列顺序。
编译器我用的是dev
#include<stdio.h>
#include<stdlib.h>
struct people {
int number;
int cripher;
people* next;
};
typedef people* poly;
poly make(int n);
poly say(int m,poly L);
poly out(poly L);
int main() {
poly L,p,L1;
int n=0,m=0,i;
scanf("%d %d", &n,&m);
L=make(n);
L1 = L;
for ( i = 1; i <= n; i++) {
scanf("%d", &L1->cripher);
L1->number = i;
L1 = L1->next;
}
for (i = 0; i < n; i++)
{
p = say(m,L);
m = p->cripher;
printf("%d\t", p->number);
L = out(p);
}
return 0;
}
poly make(int n) {
poly L, L1;
int i = 1;
L = (poly)malloc(sizeof(people));
L1 = L;
for (int i = 1; i < n; i++) {
L1->next = (poly)malloc(sizeof(people));
L1 = L1->next;
}
L1->next = L;
return L;
}
poly say(int m,poly L) {
int lastnumber= 1;
for ( ; lastnumber < m;lastnumber++) {
L = L->next;
}
return L;
}
poly out(poly L) {
poly L1,L2;
L1 = L->next;
L2 = L;
while (L1->number != L->number) {
L1 = L1->next;
L2 = L2->next;
}
L = L->next;
L2->next = L1->next;
free(L1);
return L;
}