1 #include <stdio.h>
2 #include <stdlib.h>
3
4 typedef struct list
5 {
6 int ID;
7 int PASSWORD;
8 struct list *next;
9 }LIST;
10
11 /*************函数声明**************/
12
13 void creat_list(LIST *L);//创建链表
14 void josephus(LIST *L, int cipher);//执行约瑟夫环
15
16 /*************主函数****************/
17
18 int main(void)
19 {
20 LIST L, *p = NULL;
21 int cipher;//密码
22
23 creat_list(&L);
24
25 do
26 {
27 getchar();
28 printf("请输入初始密码:");
29 scanf("%d", &cipher);
30 }while(cipher < 1);
31
32 josephus(&L, cipher);
33
34 system("pause");
35 return 0;
36 }
37
38 /*****************creat_list*********************/
39
40 void creat_list(LIST *L)
41 {
42 LIST *p, *r;
43 int i = 1, cipher;
44
45 printf("\n请输入第%d个人的密码:", i);
46 scanf("%d",& cipher);
47
48 L->ID = i++;//头插法
49 L->next = NULL;
50 L->PASSWORD = cipher;
51 r = L;
52 while(1)
53 {
54 printf("\n请输入第%d个人的密码:", i);
55 scanf("%d", &cipher);
56 if (cipher < 1)
57 {
58 break;
59 }
60
61 p = (LIST *)malloc(sizeof(LIST));
62 p->ID = i++;
63 p->next = r->next;
64 p->PASSWORD = cipher;
65 r->next = p;
66 r = p;
67 }
68 r->next = L;
69 }
70
71 /********************josephus***********************/
72
73 void josephus(LIST *L, int cipher)
74 {
75 LIST *f;//删除结点前一结点
76 LIST *p;
77 p = L;
78 f = L;
79 while (f->next != p)//初始化p的前一节点位置
80 {
81 f = f->next;
82 }
83
84 while (1)
85 {
86 while (cipher - 1 != 0)
87 {
88 f = p;
89 p = p->next;
90 cipher--;
91 }
92
93 cipher = p->PASSWORD;
94 printf("\n第%d个人出列(密码:%d)", p->ID, p->PASSWORD);
95 f->next = p->next;
96 p = p->next;
97
98 if (p == f)//表中只有一个结点
99 {
100 printf("\n第%d个人出列(密码:%d)", p->ID, p->PASSWORD);
101 return;
102 }
103 }
104 }
105
106 /*****************************************************************************/