2020-06-10

约瑟夫环 数据结构实验

一.问题描述:约瑟夫问题的一种描述为,编号为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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值