鱼C论坛

 找回密码
 立即注册
查看: 2176|回复: 1

约瑟夫环问题:要求报到数的人手中的密码作为下个报数上限值,这个密码可正可负。

[复制链接]
发表于 2020-3-24 10:59:54 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#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;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-3-24 11:04:18 | 显示全部楼层
https://blog.csdn.net/qq_33466466/article/details/79900779
很详细
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-18 23:22

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表