1197=约瑟夫问题

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 struct node
 4 {
 5     int data;
 6     struct node*next;
 7 };
 8 int main()
 9 {
10     int m,n,x,i,j;
11     struct node*head,*p,*end;
12     head=(struct node*)malloc(sizeof(struct node));
13     head->next=NULL;
14     end=head;
15     head->data=1;
16     scanf("%d %d",&n,&m);
17     for(i=0; i<n-1; i++)
18     {
19         p=(struct node*)malloc(sizeof(struct node));
20         p->data=i+2;
21         p->next=head;//环状问题,让p的下一个等于head。
22         end->next=p;
23         end=p;
24     }
25     for(j=0; j<n-1; j++)
26     {
27         p=end->next;
28         for(i=1; i<=m-1; i++)
29         {
30                 p=p->next;
31                 end=end->next;//循环次数要比m小一个,以便于下面进行删除操作。
32         }
33         end->next=p->next;
34     }
35     printf("%d",end->data);//这里要记得输出end,因为这个地方的p属于被删除的节点,end是要记录编号的地方。
36     return 0;
37 }

猜你喜欢

转载自www.cnblogs.com/Angfe/p/10485458.html