來自于《算法:C 語言實現》
1 // 約瑟夫問題-循環鏈表
2
3 #include <stdio.h>
4 #include <stdlib.h>
5
6 typedef struct node* link;
7
8 struct node
9 {
10 int item;
11 link next;
12 };
13
14 int main()
15 {
16 int i, N, M;
17 link p;
18 scanf("%d %d", &N, &M);
19 link t = (link)malloc(sizeof (*t)), x = t;
20 t->item = 1;
21 t->next = t;
22 for (i = 2; i <= N; ++i)
23 {
24 /*x = x->next = (link)malloc(sizeof (*x));
25 x->item = i;
26 x->next = t;*/
27 p = (link)malloc(sizeof (*x));
28 p->item = i;
29 x->next = p;
30 x = x->next;
31 x->next = t;
32 }
33
34 while (x != x->next)
35 {
36 for (i = 1; i < M; ++i)
37 {
38 x = x->next;
39 }
40 // x->next = x->next->next;
41 t = x->next;
42 x->next = x->next ->next;
43 free(t);
44 --N;
45 }
46 printf("%d\n", x->item);
47 free(x);
48 return 0;
49 }
posted on 2011-04-20 17:39
unixfy 閱讀(138)
評論(0) 編輯 收藏 引用