Josephus

利用循环链表模拟约瑟夫问题,把自杀的人的顺序排列出来

代码如下:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 
 4 typedef int status;
 5 
 6 typedef struct node
 7 {
 8     status data;
 9     struct node *next;
10 }LinkList;
11 
12 LinkList *create(int n)
13 {
14     LinkList *head,*p1,*p2;
15     int i;
16 
17     head=(LinkList *)malloc(sizeof(LinkList));
18     head->next=NULL;
19     p1=head;
20 
21     for(i=1;i<=n;i++)
22     {
23         p2=(LinkList *)malloc(sizeof(LinkList));
24         p2->next=p1->next;
25         p1->next=p2;
26         p1=p2;
27 
28         p1->data=i;
29 
30     }
31     p1->next=head->next;
32 
33     return head;
34 }
35 
36 void Josephus(LinkList *L)
37 {
38     LinkList *p1,*temp;
39     p1=L;
40     int i;
41 
42     while(p1!=p1->next)
43     {
44         for(i=1;i<3;i++)
45         {
46             p1=p1->next;
47         }
48 
49         printf("%d->",p1->next->data);
50         temp=p1->next;
51         p1->next=temp->next;
52 
53         free(temp);
54     }
55     printf("%d
",p1->data);
56     printf("
");
57 }
58 
59 int main()
60 {
61     LinkList *head;
62     int n;
63 
64     scanf("%d",&n);
65 
66     head=create(n);
67     Josephus(head);
68 
69     return 0;
70 }
View Code
原文地址:https://www.cnblogs.com/52Cassie/p/4817614.html