循环链表模版--约瑟夫

南楼画角 提交于 2020-03-01 14:27:02

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int n,m;
typedef struct node
{
    int date;
    struct node *next;
}node;

int main()
{
    int i,sum=0,count=0;
   scanf("%d%d",&n,&m);
   node *tail,*head,*p,*q;
   head=(node *)malloc(sizeof(node));
   head->date=1;
   head->next=NULL;
   tail=head;
   for(i=2;i<=n;i++)
   {
       p=(node *)malloc(sizeof(node));
       p->date=i;
       p->next=NULL;
       tail->next=p;
       tail=p;
   }
   tail->next=head;
   for(q=head;q->next!=head;)
     q=q->next;
   while(count<n-1)
   {
       p=q->next;
       sum++;
       if(sum%m==0)
       {
           q->next=p->next;
           free(p);
           count++;
       }
       else q=p;
   }
   printf("%d\n",q->date);


  return 0;
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!