用链表实现约瑟夫环

话说输入N, 表示1~n个数, 在输入m,表示要删除的数。代码如下:

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 scanf( "%d", &m );
14 head = p1 = (struct student *)malloc(LEN);
15 head->num = 1;
16 for( i = 2; i <= m; i++ )
17 {
18 p1->next = (struct student *)malloc(LEN);
19 p1 = p1->next;
20 p1->num = i;
21 } //1~n个数存入链表
22 p1 -> next = head;
23 int j;
24 scanf( "%d", &j );
25 while(m!=1)
26 {
27 for( i = 1; i < j; i++ )
28 p1 = p1->next;
29 p2 = p1->next;
30 printf( "node:%d\n", p2 -> num );
31 p1 -> next = p2 -> next;
32 free(p2);
33 //删除第j个数
34 m--;
35 }
36 printf("%d\n",p1->num);
37 system( "pause" );
38 return 0;
39 }
原文地址:https://www.cnblogs.com/zsj576637357/p/2361949.html