约瑟夫环双向列表之终极优化

来源:互联网 发布:经传软件三板斧不准 编辑:程序博客网 时间:2024/06/03 03:31
#include<stdio.h>#include<stdlib.h>typedef struct Node{    Node *pre;    Node *next;    int data;} *List;void Init(List &l,int n){    Node *p,*current;    p=(List)malloc(sizeof(Node));        p->pre=NULL;        p->next=NULL;        p->data=1;    l=p;    current=p;    for(int i=2;i<=n;i++)    {        p=(List)malloc(sizeof(Node));        p->pre=current;        p->next=NULL;        p->data=i;        current->next=p;        current=p;    }    l->pre=current;    current->next=l;}void showList(List l,int n){    for(int i=1;i<=n;i++)    {        printf("%d\t",l->data);        l=l->next;    }    printf("\n");}int main(){    int n,m;    scanf("%d%d",&m,&n);    List l,p,pd;    Init(l,n);     p=l->pre;    pd=p->next;    int len=n;    while(len!=1)    {        //showList(l,len);        int Kount=0,m1=m%len;        if(m1<=len/2)        while(Kount!=(m%len))//移动方式根据m'的不同而进行相应的调整,当m'比较大的时候,就往左移,相反,就往右边移动        {            p=p->next;            pd=p->next;            Kount++;        }        else if(m1>len/2)        {            while(Kount!=len-m1)            {                p=p->pre;                pd=p->next;                Kount++;            }        }        p->next=pd->next;        free(pd);        pd=NULL;        l=p->next;        l->pre=p;        pd=p->next;        len-- ;    }    printf("%d\n",l->data);    return 0;}