模拟约瑟夫环程序

13个人围成一圈,从第一个人开始顺序报数1,2,3。凡报到3者退出圈子。找出最后留在圈子中的人原来的序号。

#include<stdio.h>
#include<stdlib.h>         //malloc要用到
struct node
{
 int data;
 struct node *next;
};

node *create(int n)
{
 node *h,*r,*p;
 h=(node *)malloc(sizeof(node));
 h->data=1;                         //从1开始
 r=h;
 int i;
 for(i=2;i<=n;i++)
 {
  p=(node *)malloc(sizeof(node));
  p->data=i;
  r->next=p;
  r=p;
 
 }
 r->next=h;                        //连接成环
 return h;
}

void je(node *p,int m)
{
 node *q;
 int i=0;
 do
 {
  i++;
  if(i==m-1)
  {
   q=p->next;
   printf("%d\n",q->data);
   p->next=q->next;
   free(q);   //记得释放空间
   i=0;  
  }
 p=p->next;
 }while(p->next!=p);
 printf("%d\n",p->data);          //最后剩下的那个节点
 free(p);
}

int main()
{
 int n,m;
 printf("input n,m:\n");          //输入人数和报号数
 scanf("%d %d",&n,&m);
 node *p;    
 p=create(n);                     //创建环
 je(p,m);       //调用出环函数
 return 0;
}

posted @ 2011-09-19 08:39  auleaf  阅读(205)  评论(0编辑  收藏  举报