约瑟夫问题

来源:互联网 发布:西门子编程线 编辑:程序博客网 时间:2024/06/06 07:01
#include <iostream>#include <algorithm>#include <string>#include <cstdio>using namespace std;typedef struct node{    int data;    node *next;}Linklist;Linklist *head, *p, *tail, *q;/*void nxcreat(int n)///逆序键链表{    head=new Linklist;    head->next=NULL;    while(n--)    {        p=new Linklist;        cin>>p->data;        p->next=head->next;        head->next=p;    }}*/void creat(int n)///建循环链表{    int x=1;    head=new Linklist;    head->next=NULL;    tail=head;    while(n--)    {        p=new Linklist;        p->data=x;        p->next=NULL;        tail->next=p;        tail=p;        x++;    }    tail->next=head->next;}int killpeo(int n, int m){    int num=0;    p=head;    while(n!=1)    {        q=p->next;        num++;        if(num%m==0)        {            p->next=q->next;            n--;            free(q);        }        else            p=q;    }    return p->data;}void display(Linklist *head){    p=head->next;    while(p->next)    {        cout<<p->data<<" ";        p=p->next;    }    cout<<p->data<<endl;}int main(){    ios::sync_with_stdio(false);    int n, m;    cin>>n>>m;    creat(n);    cout<<killpeo(n, m)<<endl;    return 0;}

0 0