试用循环链表为存储结构,写一个约瑟夫问题的算法。
发布网友
发布时间:2022-05-24 07:15
我来回答
共1个回答
热心网友
时间:2023-10-08 16:41
#include<stdlib.h> /*杂类声明*/
#include<stdio.h>
struct dnode{
int num, key;
struct dnode *prior,*next;
};
void main(){
int n,m,i,k;
struct dnode *head,*p,*s;
printf("________________________________________________________________________________");
printf("--------------------------------------------------------------------------------");
printf("\t\t\t The question of YSFH\n\n\n");
printf("Please input num of person and first password:");
scanf("%d,%d",&n,&m);
printf("\n");
while(n<0||m<0){ /*当人数小于零,或者初始密码小于零时报错,重新输入*/
printf("error!num,password should >0\n");
scanf("%d,%d",&n,&m);
}
s=(struct dnode*)malloc(sizeof(struct dnode));
for(i=1;i<=n;i++){
if(i==1)
head=s;
p=s; /*P指向新建的接点*/
p->num=i;
printf("Please input %d password:", i);
scanf("%d",&p->key);
printf("\n");
while(p->key<0){ /*当密码小于零时报错,重新输入*/
printf("error!password should >0\n");
scanf("%d",&p->key);
}
s=(struct dnode*)malloc(sizeof(struct dnode)); /*创建下一个结点,*/
/*连接在P后*/
p->next=s; /*创建下一个结点,连接在P后*/
s->prior=p;
}
p->next=head; /*所有结点创建完毕,把尾指针与头指针相连*/
head->prior=p;
free(s);
p=head;
printf("\n\nDequeue Sequence :\t");
for(i=1;i<=n;i++){
for(k=1;k<=m;k++) /*找到要删除结点的下一个结点,并保存要删除结点*/
p=p->next; /*中的密码,以作为下次循环的条件*/
m=p->prior->key;
printf(" --> %d",p->prior->num);
p->prior->prior->next=p; /*删除结点,作结点前后结点的连接*/
p->prior=p->prior->prior;
if(i%8==0)
printf("\n\t\t\t");
}
for(i=1;i<5;i++)
printf("\n");
printf("----------------------------------------------------------------------------[YM]");
printf("________________________________________________________________________________");
getch(); /*使运行时画面停留在结果处*/
}
参考资料:唯C期刊上的