第一次用链表!【练习】

来源:互联网 发布:iphone 读书软件 编辑:程序博客网 时间:2024/05/21 07:11
/*n 个人围成一个圆圈,第1个人从1开始顺时针报数,  报到m的人,令其出列。然后再从下一个人开始,从1顺时针报数,报到第m个人,再令其出列,…,如此下去,  直到圆圈中只剩一个人为止。此人即为优胜者。要求 输入 n 和m,      输出优胜者例如  n = 8   m = 3*/#include<stdio.h>#include<malloc.h>typedef struct Dulnode{int num;struct Dulnode *next;}Dulnode, *Node;Node  InitDul(Node L){Node p;if(!(p = (Node)malloc(sizeof(Dulnode)) ) )return 0;p->next = NULL;L = p;return L;}Node CreatDul(Node L, int n){Node p, q;int i;p = L;p->num = 1;for(i = 2; i <= n; i++){if( !(q = (Node)malloc( sizeof(Dulnode) )))return 0;q->num = i;p->next = q;p  = q;}p->next = L;return L;}int SolveDul(Node L, int n, int m){int i, j;Node p, q;p = L;for(i = 1; i < n; i++){for(j = 1; j <= m-2; j++)p = p->next;q = p->next;p->next = q->next;free(q);p = p->next;}return p->num;}int main(){int n, m, ans;Node L;while(scanf("%d %d", &n, &m) != EOF){if(m == 1)printf("%d\n", n);else{L = InitDul(L);L = CreatDul(L, n);ans = SolveDul(L,n,m);printf("%d\n", ans);}}return 0;}

纪念一下!
0 0
原创粉丝点击