约瑟夫环

 1 #include <iostream>
 2 #include <stdlib.h>
 3 
 4 using namespace std;
 5 
 6 typedef struct LinkNode{
 7     int data;
 8     struct LinkNode* next;
 9 }JosephuNode;
10 
11 
12 int Josephu(int n, int m)
13 {
14 
15     //creat
16     JosephuNode *head, *tail;
17     head = tail = (JosephuNode*) malloc(sizeof(JosephuNode));;
18 
19     for(int i = 1; i < n; i++)
20     {
21         tail->data = i;
22         tail->next = (JosephuNode*)malloc(sizeof(JosephuNode));
23         tail = tail->next;
24     }
25     tail->data = n;
26     tail->next = head;
27 
28 
29     //loop
30     while(tail != head)
31     {
32         for(int j = 1; j < m; ++j)
33         {
34             tail = head;
35             head = head->next;
36         }
37         tail->next = head->next;
38         cout<<head->data<<endl;
39         free(head);
40         head = tail->next;
41     }
42 
43     int last = head->data;
44     free(head);
45     head = tail = NULL;
46 
47     return last;
48 }
49 
50 
51 int main()
52 {
53     int n,m;
54     cout<<"input n and m:"<<endl;
55     cin>>n>>m;
56     int last = Josephu(n, m);
57     cout<<"Last number is:"<<last<<endl;
58 
59 
60     return 0;
61 }
View Code
 1 #include<iostream>
 2 #include<list>
 3 #include<fstream>
 4 using namespace std;
 5 int main()
 6 {
 7     int m,n,temp,i,j;
 8     FILE *out;
 9     out=fopen("out","w");
10     cout<<"input n and m:"<<endl;
11     cin>>n>>m;
12     int a[n];
13     for(i=1;i<=n;i++)
14         a[i]=i;
15     a[0]=0;
16     i=0;
17     temp=n;
18     while(temp)
19     {
20         for(j=0;j<m;)
21         {
22             i=(i)%n+1;
23             if(a[i]!=0)
24                 j++;
25 
26         }
27 
28         cout<<a[i]<<endl;
29         fprintf(out, "%d\n", a[i]);
30         a[i]=0;
31         temp--;
32 
33     }
34     fclose(out);
35 
36 
37     return 0;
38 }
39 //数组
View Code

 

posted @ 2016-05-05 10:59  天气晚来秋  阅读(186)  评论(0编辑  收藏  举报