posts - 183,  comments - 10,  trackbacks - 0
来自于《算法: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 阅读(125) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理