约瑟夫问题

来源:互联网 发布:成都网络推广外包 编辑:程序博客网 时间:2024/06/05 02:25

#include
#include

typedef struct node
{
 int data;
 struct node *next;
}node;

node *create(int n)
{
 node *p=NULL,*head;
 head=(node*)malloc(sizeof(node));
 p=head;
 node *s;
 int i=1;
 if (0!=n)
 {
  while (i<=n)
  {
   s=(node*)malloc(sizeof(node));
   s->data=i++;
   p->next=s;
   p=s;
  }
  s->next=head->next;
 }
 free(head);
 return s->next;
}

int main()
{
 int n;
 int m;
 scanf("%d,%d",&n,&m);
 printf("\n");
 int i;
 node *p=create(n);
 node *temp;
 m%=n;
 while (p!=p->next)
 {
  for (i=1;i
  {
   p=p->next;
  }
  printf("%d->",p->next->data);
  temp=p->next;
  p->next=temp->next;
  free(temp);
  p=p->next;
 }
 printf("%d\n",p->data);
 return 0;
}

0 0
原创粉丝点击