编写程序实现约瑟夫(Josephu)问题(C)

    技术2022-05-11  123

    #include  < stdio.h >   struct  node{ int  id; int  password; struct  node *  next;}l;del( int  m){     struct  node *  p;     struct  node *  next;     int  j;    next =& l;     for (j = 1 ;j <= 5 ;j ++ )    {         /* printf("id为%d的下个结点为%d ",next->id,next->next->id); */         next = next -> next;    }    next =& l;     while  (next -> id != next -> next -> id)    {             for (j = 1 ;j <= m;j ++ ) next = next -> next;        p = next -> next;        printf( " 删除第[%d]个结点 " ,p -> id );        next -> next = next -> next -> next;        m = next -> password;    }    printf( " complete " );    getch();}initl( int  n, int  m, int  k){     struct  node *  p, * next;     int  j;    l.password = k;    l.id = 1 ;    l.next =& l;    next =& l;    printf( " 建立链表结点[1] password=%d " ,m);     for  (j = 2 ;j <= n;j ++ )    {        p = ( struct  node * )malloc( sizeof ( struct  node));next -> next = p;next = p;p -> id = j;p -> password  = rand();p -> next =& l;    printf( " 建立链表结点[%d] password=%d " ,p -> id,p -> password);    }    del(m);}main(){     /* m为祲密码n为结点个数k */      int  n,m,k;    printf( " 请输入结点个数n: " );    scanf( " %d " , & n);    printf( " 请输入初始密码k: " );    scanf( " %d " , & k);    printf( " 请输入删除结点时的随机数m: " );    scanf( " %d " , & m);    initl(n,m,k);    }  

    最新回复(0)