狗狗约瑟夫环(链表)

Description

一天粒粒想到我们实验室玩个小游戏!n个人围成一圈!一起报数!报到第m的时候!那个报m的退出!又从1开始报!依次类推!只到剩下一个人为止!ACMer丹丹想知道那些位置的人依次退出!ACMer抛抛想知道最后是一个人是那个位置!做为聪明的ACMer请设计一个程序告诉她们吧!(位置编号从1开始顺时针到n)用循环链表写

Input

输入二个数 n 和 m。

Output

输出依次退出的位置编号!每个一行!以及最后一个留下的人的位置编号!

Sample Input

1 2 5 3

Sample Output

1 3 1 5 2 4
 
 
 
View Code
 1 #include <stdio.h>
2 #include <malloc.h>
3 #define LEN sizeof(struct student)
4 struct student
5 {
6 int num;
7 struct student *next;
8 };
9 int main()
10 {
11 struct student *head,*p1,*p2;
12 int i,m;
13 while( scanf( "%d", &m ) == 1 )
14 {
15 head = p1 = (struct student *)malloc(LEN);
16 head->num = 1;
17 for( i = 2; i <= m; i++ )
18 {
19 p1->next = (struct student *)malloc(LEN);
20 p1 = p1->next;
21 p1->num = i;
22 } //1~n个数存入链表
23 p1 -> next = head;
24 int j;
25 scanf( "%d", &j );
26 while(m!=1)
27 {
28 for( i = 1; i < j; i++ )
29 p1 = p1->next;
30 p2 = p1->next;
31 printf( "%d\n", p2 -> num );
32 p1 -> next = p2 -> next;
33 free(p2);
34 //删除第j个数
35 m--;
36 }
37 printf("%d\n",p1->num);
38 }
39 // system( "pause" );
40 return 0;
41 }

原文地址:https://www.cnblogs.com/zsj576637357/p/2382615.html