约瑟夫问题:
N个人围成圆圈,从1开始报数,到第M个人令其出列,然后下一个人继续从1开始报数,到第M个人令其出列,如此下去,直到只剩一个人为止。显示最后一个人为剩者。
- /* 约瑟夫环
- by zzr
- http://blog.csdn.net/ZhengZhiRen/ */
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct node
- {
- int i;
- struct node *next;
- }node;
- void fun(node *p, int i)
- {
- int count=1;
- node *q;
- q=p;
- /*使q指向p之前的结点*/
- while (q->next!=p)
- q=q->next;
- /*出圈*/
- while (p->next!=p)
- {
- if (count%i==0)
- {
- q->next=p->next;
- printf( "%d " ,p->i);
- free(p);
- }
- else
- q=q->next;
- p=q->next;
- count++;
- }
- printf( "%d/n" ,q->i);
- }
- void main()
- {
- int i;
- int num;
- node *circle;
- node *p;
- node *q;
- printf( "please input number:/n" );
- scanf( "%d" ,&num);
- /*初始化循环链表*/
- circle=(node*)malloc( sizeof (node));
- circle->i=1;
- circle->next=circle;
- p=circle;
- for (i=2;i<=100;i++)
- {
- q=(node*)malloc( sizeof (node));
- q->i=i;
- q->next=p->next;
- p->next=q;
- p=p->next;
- }
- fun(circle,num);
- }