约瑟夫环的数组实现
1 /*约瑟夫环的实现*/
2 #include<stdio.h>
3 #include<stdlib.h>
4 #include<time.h>
5
6 #define SIZE 10
7 #define STEP 5
8
9 void initArray(int arr[SIZE]);
10 void joseph_1();
11 void joseph_2();
12
13 int main()
14 {
15 joseph_2();
16 return 0;
17 }
18
19 void initArray(int arr[SIZE])
20 {
21 int i;
22 for(i = 0; i < SIZE; i++)
23 arr[i] = i+1;
24 }
25
26 /*建立一个SIZE个元素的循环数组,从数组头开始遍历并计数,
27 *如果计数i == STEP则剔除元素,继续循环,
28 *当当前元素与下一个元素相同时退出循环。
29 * */
30 void joseph_1()
31 {
32 int count;//计数
33 int next;//下一个数数元素的下标
34 int move;//删除一个元素后,其后的元素前移的工作指针
35 int currentNum;//记录剩下的元素个数
36 int arr[SIZE];
37
38 next = 0;
39 currentNum = SIZE;
40 initArray(arr);
41
42 while(currentNum != 1)
43 {
44 count = 1;
45 while(count != STEP)
46 {
47 //到达最右端
48 if(next + 1 == currentNum)
49 next = 0;
50 else
51 next++;
52 count++;
53 }
54 //打印出队的元素
55 printf("%2d->",arr[next]);
56 //next后的元素前移
57 for(move = next + 1; move < currentNum; move++)
58 arr[move-1] = arr[move];
59 //如果剔除的所最有端元素,下一个数数的元素应该所第一个,否则不变
60 if(next + 1 == currentNum)
61 next = 0;
62 currentNum--;
63 }
64 printf("
The winner is :%d
",arr[0]);
65 }
66 //将数到的元素置零,只需找到最后一个非零元素即可
67 void joseph_2()
68 {
69 int i;//工作指针
70 int count;//计数
71 int currentNum;//记录剩下的元素个数
72 int next;
73 int arr[SIZE];
74
75 count = 0;
76 next = 0;
77 currentNum = SIZE;
78 initArray(arr);
79
80 while(currentNum != 1)
81 {
82 if(arr[next] != 0)
83 {
84 count++;
85 if(count == STEP)
86 {
87 printf("%2d->",arr[next]);
88 arr[next] = 0;
89 count = 0;
90 currentNum--;
91 }
92 else
93 next = (next + 1) % SIZE;
94 }
95 else
96 next = (next + 1) % SIZE;
97 }
98 //找到最后一个非零元素
99 for(i = 0; i < SIZE; i++)
100 if(arr[i] != 0)
101 printf("
The winner is:%d
",arr[i]);
102 }
约瑟夫环的链表实现:
1 #include<stdio.h> 2 #include<stdlib.h> 3 4 typedef struct Node 5 { 6 int data; 7 struct Node* next; 8 }NODE; 9 10 //初始化链表 11 NODE *init(int n); 12 //从K个人开始计数,数到M的人退出圈 13 void link(NODE *head, int k, int m); 14 15 int main() 16 { 17 NODE *head = init(10); 18 link(head,1,5); 19 return 0; 20 } 21 22 //初始化链表 23 NODE *init(int n) 24 { 25 int i; 26 NODE *head,*pcur,*pnew; 27 28 //创建第一个结点 29 head = (NODE*)malloc(sizeof(NODE)); 30 head->data = 1; 31 pcur = head; 32 33 //创建后面的结点 34 for(i = 2; i <= n; i++) 35 { 36 pnew = (NODE*)malloc(sizeof(NODE)); 37 pnew->data = i; 38 39 pcur->next = pnew; 40 pcur = pnew; 41 } 42 //形成环 43 pcur->next = head; 44 return head; 45 } 46 47 48 //从K个人开始计数,数到M的人退出圈 49 void link(NODE *head, int k, int m) 50 { 51 NODE *pcur, *ppre; 52 int i; 53 54 pcur = head; 55 //将指针移动到第K的人处 56 while(pcur->data < k) 57 pcur = pcur->next; 58 59 while(pcur->next != pcur) 60 { 61 for(i = 1; i < m; i++) 62 { 63 ppre = pcur; 64 pcur = pcur->next; 65 } 66 //打印出队元素 67 printf("->%2d",pcur->data); 68 //出队 69 ppre->next = pcur->next; 70 free(pcur); 71 pcur = ppre->next; 72 } 73 printf("->%2d",pcur->data); 74 printf(" The winner is %d ",pcur->data); 75 //释放最后一个结点 76 free(pcur); 77 }