数据局结构编程,求救,分有!有编号为1、2、·····n的n个人围成一圈,约定编号为k(1<=k<=n)的人从1

2025-03-10 04:54:00
推荐回答(3个)
回答1:

你好,不知道你有没有理解错,数据结构是一种数据存储结构,不是一门语言。此题我用比较
通用的C++来编写,代码里面只有少量注释,如果不懂欢迎追问!
代码如下:

#include
struct Cricle
{
int *NumCan;
int len;
};//用来模拟游戏队伍

int *Order;//用来存储出列顺序

void main()
{
int n,m;//人数和m
int pos=-1;//开始的位置
cout<<"请输入参与游戏的人数:";
cin>>n;
Cricle *Group;
Group=new Cricle;
Group->NumCan=new int[n];
Order=new int[n];
Group->len=n;
while(1)
{
cout<<"请确定开始位置(1-"< cin>>pos;
if(pos<=n&&pos>=1)break;
else cout<<"输入位置错误!"< }
pos--;
cout<<"请输入m的值:";cin>>m;
cout<<"开始游戏:"< int k;
for(int i=0;iNumCan[i]=1;//表示人在队伍里
while(Group->len)
{
pos=(pos+m)%n;//此处采用取余,即体现了循环的思想
if(!Group->NumCan[pos])continue;//如果该位置没人,继续循环;
//有人
cout< Group->NumCan[pos]=0;
Group->len--;
Order[Group->len]=pos;
}
cout<<"游戏结束!"< cout<<"出列顺序为:"< for(i=1;i cout< cout<}

回答2:

你好:这个问题是“约瑟夫环”
下面是我读书的时候写的代码,翻箱倒柜给你找出来的。但是你一定要养成自己编写的好习惯。希望这个对你的学习有帮助……

#include "stdlib.h"
#include "stdio.h"
#include "conio.h"
#define NULLL 0

typedef struct linknoder
{
elemtype datar;
struct linknoder *nextr;
}nodetyper;
int i,m;
nodetyper *creatt(int n)
{
nodetyper *s,*r=NULL,*h;
int i;
for(i=1;i<=n;i++)
{s=(nodetyper*)malloc(sizeof(nodetyper));
s->datar=i;s->nextr=NULL;
if(i==1)h=s;
else r->nextr=s;
r=s;}
r->nextr=h;
return h;}
void printt(n)
{printf("小孩原来的顺序为:\n");
for(i=1;i<=n;i++)
{printf("%3d",i);
if(i%10==0)printf("\n");}
printf("\n");
}
void jese(nodetyper *h,int k)
{
int i;
nodetyper *p=h,*q;
printf("游戏结束后小孩的出队顺序如下输出\n");
while(p->nextr!=p)
{
for(i=1;i p=p->nextr;
if(p->nextr!=p)
{q=p->nextr;
printf("%3d",q->datar);
p->nextr=q->nextr;
free(q);}
p=p->nextr;}
printf(" ");
printf("\n");
printf("幸运当选为大王的孩子是:\n");
printf("%d",p->datar);
}

youxi()
{int n,k;
nodetyper *h;
clrscr();
textcolor(2);
printf("***********************欢迎您参加本游戏************************:\n");
printf("游戏简介:给定任意的正整数n,k将n当做参与这项游戏的小孩数:\n");
printf("k当作游戏的密码将所有的小孩按序号1.2.3...排列成一个环行:\n");
printf("从第一个小孩开始,以k 为密码沿顺时针方向第 k 个小孩出队\n");
printf("依次类推直到所有的人都出列,系统会给出小孩顺序变化的比较:\n");
printf("最后出列的孩子将幸运的被选为这群孩子中的大王,十分有趣:\n");
printf("请输入游戏人数:\n");
scanf("%d",&n);
h=creatt(n);
printf("请输入游戏密码k\n");
scanf("%d",&k);
printt(n);
jese(h,k);
getch();}

很多年前的代码了。当时才开始学C和数据结构。代码比较幼稚,呵呵!

回答3:

用不带头结点的循环链表,每出列一个则摘除一个结点,直到最后 一个