约瑟夫环

来源:互联网 发布:公司财务战略矩阵 编辑:程序博客网 时间:2024/04/26 08:48
#include<stdio.h>
#define LEN sizeof(struct JosNode)
struct JosNode
{
 int pwd;
 int ord;
 struct JosNode *next;
};
void Joseph(int *m,struct JosNode *p);
struct JosNode *creat(int n);
struct JosNode *Move(struct JosNode *head);
void main()
{
 int n;
 int passwd;
 /*clrscr();*/
 /*system("cls");*/
 printf("请输入初始的人数n和初值密码m:/n");
 scanf("%d%d",&n,&passwd);
 Joseph(&passwd,Move(creat(n)));
}
struct JosNode *creat(int n)
{
 struct JosNode *head;
 struct JosNode *p1,*p2;
 int i=0;
 p1=p2=(struct JosNode *)malloc(LEN);
 head=NULL;
 while(i<n)
 {
  printf("输入第%d个人的密码:",i+1);
  scanf("%d",&p1->pwd);
  i++;
  p1->ord=i;
  if(i==1) head=p1;
  else p2->next=p1;
  p2=p1;
  p1=(struct JosNode *)malloc(LEN);
 }
 p2->next=head;
 return (head);
}
struct JosNode *Move(struct JosNode *head)
{
 struct JosNode *p;
 for(p=head;head->next!=p;head=head->next);
 return head;
}
void Joseph(int *m,struct JosNode *p)
{
 int i;
 struct JosNode *q;
 printf ("出队编号如下:/n");
 while (p->next!=p)
 {
  for (i=1;i<=*m;i++)
   p=p->next;
  printf ("%d/t",p->ord);
  *m=p->pwd;
  for(q=p;p->next!=q;p=p->next);
  p->next=q->next;
  free(q);
 }
 printf("%d/n",p->ord);
}
/*递归实现*/
/*
void Joseph(int password,struct JosNode *head)
{
 int k,i=1;
 struct JosNode *h=head;
 struct JosNode *p=NULL;
 while(i<password)
 {
  p=h;
  h=h->next;
  i++;
 }
 printf("/t%d",h->ord);
 head=h->next;
 if(p!=NULL)
 {
  k=h->pwd;
  p->next=h->next;
 }
 else
 {
  head->next=NULL;
  printf("/t%d",head->ord);
 }
 if(head->next==head)
  printf("/t%d",head->ord);
 free(h);
 if(head->next!=head&&head->next!=NULL)
  Joseph(k,head);
}
*/