约瑟夫环

#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);
}
*/ 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bill Adams

喜欢?打赏一杯阔乐吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值