Circular list example -- Josephus problem

来源:互联网 发布:个性淘宝女装店名 编辑:程序博客网 时间:2024/04/29 22:14
  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. typedef struct node* link;
  4. struct node
  5. {
  6.     int item;
  7.     link next;
  8. };

  9. int main( int argc, char *argv[] )
  10. {
  11.     int i, N = atoi( argv[1] ), M = atoi( argv[2] );
  12.     link t = malloc( sizeof *t ), x = t;
  13.     t->item = 1;
  14.     t->next = t;
  15.     for ( i = 2; i <= N; i++ )
  16.     {
  17.         x = ( x->next = malloc( sizeof *t ) );
  18.         x->item = i;
  19.         x->next = t;
  20.     }
  21.     while ( x != x->next )
  22.     {
  23.         for ( i = 1; i < M; i++ )
  24.             x = x->next;
  25.         x->next = x->next->next;
  26.         N--;
  27.     }
  28.     printf( "%d/n", x->item );
  29.     return 0;
  30. }
from Robert Sedgewick's Alorithms in C