约瑟夫环问题:要求报到数的人手中的密码作为下个报数上限值,这个密码可正可负。
#include<stdio.h>#include<stdlib.h>
#include<time.h>
typedef struct node{
int data;
int key;
struct node *next,*pre;
}node;
node *createnc(int n){
node *p =NULL;
node *q =NULL;
node *head,*s;
head=(node*)malloc(sizeof(node));
p=head;
int i;
srand(time(NULL));
i=1;
if(n!=0){
while(i<=n){
s=(node*)malloc(sizeof(node));
s->data=i++;
s->key=rand()%11-5;
while(!s->key){
s->key=rand()%11-5;
}
printf("第%d个人的密码是%d\n",s->data,s->key);
q=p;
p->next=s;
p=s;
p->pre=q;
}
s->next=head->next;
}
free(head);
return s->next;
}
int main(){
srand(time(NULL));
int n=rand()%10+1;
int m=rand()%10+1;
printf("一共有%d人\n",n);
printf("报数上限值是%d\n",m);
int i;
node *p=createnc(n);
node *q;
m%=n;
while(p!=p->next){
if(m>1){
for(i=1;i<m-1;i++){
p=p->next;
}
printf("%d->",p->next->data);
m=p->next->key;
q=p->next;
p->next=q->next;
free(q);
p=p->next;
}
else if(m<0){
m=-m;
for(i=1;i<m;i++){
p=p->pre;
}
printf("%d->",p->pre->data);
m=p->pre->key;
q=p->pre;
p->pre=q->pre;
free(q);
p=p->pre;
}
else if(m==1){
printf("%d->",p->data);
m=p->next->key;
q=p->next;
p->next=q->next;
free(q);
p=p->next;
}
}
printf("%d\n",p->data);
return 0;
} https://blog.csdn.net/qq_33466466/article/details/79900779
很详细
页:
[1]