约瑟夫环问题

来源:互联网 发布:java 读取表单文件 编辑:程序博客网 时间:2024/06/05 04:18
 #include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node *next;
};
struct node *creat(int n)
{
    struct node *head,*p,*tail;
    p=(struct node*)malloc(sizeof(struct node));
    p->data=1;
    p->next=NULL;
    head=p;
    tail=p;
    for(int i=2;i<=n;i++)
    {
        p=(struct node*)malloc(sizeof(struct node));
        p->data=i;
        tail->next=p;
        tail=p;
        p->next=NULL;
    }
    tail->next=head;
    return head;
}
int xuan(struct node *head,int m,int n)
{
    int num=0;
    int count=0;
    struct node*p,*q;
    q=head;
    while(q->next!=head)
         q=q->next;
    while(count<n-1)
    {
        p=q->next;
        num++;
        if(num%m==0)
        {
            q->next=p->next;
            free(p);
            count++;
        }
        else
            q=p;

    }
    return q->data;
}
int main()
{
    int n,m;
    struct node *head;
    scanf("%d%d",&n,&m);
    head=creat(n);
    printf("%d\n",xuan(head,m,n));
    return 0;
}
1 0