链表---约瑟夫问题

来源:互联网 发布:txt电子书制作软件 编辑:程序博客网 时间:2024/06/05 18:12

代码:

  1 #include  <iostream>  2 using namespace std;  3   4 #include <stdlib.h>  5 #include <stdio.h>  6   7 #define N  8  8 #define  M   3  9  10 struct Jew{ 11         int number; 12         Jew* next; 13 }; 14  15 int main() 16 { 17  18         Jew * jew; 19         Jew *  r; 20  21         jew = (Jew *)malloc(N * sizeof(Jew)); 22  23         if( jew == NULL) 24         { 25                 printf("Memory alloc fail!\n"); 26                 return  -1; 27         } 28  29                r=jew; 30                int i; 31                for( i =1;i<N;i++) 32                { 33                 r->number = i; 34                 printf("r->number=%d\n",i); 35                 r->next = jew  + i; 36                 r = r->next; 37                } 38  39                r->number = N; 40                 printf("r->number=%d\n",i); 41                 r-> next = jew; 42  43                while( r != r->next) 44                { 45                 int j; 46                 for(j=0;j<M-1;j++) 47                 { 48                         r = r->next; 49                 } 50                 printf("%4d",r->next->number); 51                 r->next = r->next->next; 52                } 53                printf("\n When N =8,M=3,joswphus,hiding in position %d survives.\n",r->number); 54  55                free(jew); 56  57         return 0; 58 }                                                                                                                                 



遇到的问题:

       #define N 8;后面不能加分号,加了分号还会出现上篇文章中出现的问题。

        

0 0