其他分享
首页 > 其他分享> > Josephus问题的实现

Josephus问题的实现

作者:互联网

 

这里使用队列来解决。

因为我们处理的是n个元素里面的第m个元素,如果每次从队列里一边取元素,一边又加到队列的末尾,数到第m的时候,这第m的元素直接出队,不再入队。依此循环n遍,可以按所需顺序移除掉n个元素。

C++代码如下:

 1 #include <iostream>
 2 #include <stdlib.h>
 3 using namespace std;
 4 
 5 struct Node
 6 {
 7     int data;
 8     struct Node* next;
 9 };
10 typedef struct Node* queue;
11 typedef struct Node* position;
12 //创建队列
13 queue create_queue(int N)
14 {
15     queue Q = (queue)malloc(sizeof(Node));
16     Q->next = NULL;
17     position r=NULL;
18     for (int i = 1; i <= N; i++)
19     {
20         position p = (position)malloc(sizeof(Node));
21         p->data = i;
22         if (Q->next == NULL)
23             Q->next = p;
24         else
25             r->next = p;
26         r = p;
27     }
28     r->next = NULL;
29     return Q;
30 }
31 //出队
32 position Dequeue(queue Q)
33 {
34     if (Q->next == NULL)
35     {
36         cout << "queue is empty" << endl;
37         exit(1);
38     }
39     else
40     {
41         position front = Q->next;
42         Q->next = front->next;
43         front->next = NULL;
44         return front;
45     }
46 }
47 //入队
48 void Enqueue(queue Q,position p)
49 {
50     position r=Q;
51     position rear = (position)malloc(sizeof(Node));
52     if (rear == NULL)
53     {
54         cout << "out of space";
55         exit(1);
56     }
57     while(r ->next!= NULL)
58         r = r->next;
59     r->next = rear;
60     rear->data = p->data;
61     rear->next = NULL;
62     free(p);
63 }
64 //Josephus
65 void Josephus(queue Q, int N,int M)
66 {
67     position p,r=Q;
68     for (int i = 0; i <N; i++)//循环N次
69     {
70         for (int j = 0; j < M-1; j++)//出队和入队M-1次
71         {
72             p=Dequeue(r);//出队
73             Enqueue(r,p);//入队
74         }
75         p = Dequeue(r);//出队第M次结点,但不再入队
76         cout<<p->data<<" ";
77     }
78 }
79 int main()
80 {
81     queue Q=create_queue(10);
82     Josephus(Q,10,5);
83     system("pause");
84     return 0;
85 }

运行结果:

标签:Node,queue,Josephus,实现,next,问题,int,position,NULL
来源: https://www.cnblogs.com/cs0915/p/12152078.html