约瑟夫环(循环链表实现)

来源:互联网 发布:拿破仑全面战争mac 编辑:程序博客网 时间:2024/04/20 00:45
#include <iostream>#include <malloc.h>using namespace std;struct jeseph{    int data;    struct jeseph* next;};struct jeseph *create(struct jeseph* head,int n){    struct jeseph *p=head,*s;    for (int i=1;i<=n;i++)    {        s=(struct jeseph*)malloc(sizeof(struct jeseph));        s->data=i;        p->next=s;        p=s;    }    p->next=head->next;    free( head);    return p->next;}int main(){    int n,m,i;    struct jeseph* head,*t;    head=(struct jeseph*)malloc(sizeof(struct jeseph));    cin>>n>>m;    struct jeseph* start=create(head,n);    struct jeseph* h=start;    while (h!=h->next)    {        for (i=1;i<m-1;i++)        {            h=h->next;        }        t=h->next;        h->next=t->next;        h=t->next;        free (t);    }    cout<<h->data<<endl;    return 0;}

约瑟夫环问题的几种解决方法:

打表法,这个比较容易理解

递归:理解稍微有点难,但是真的非常简洁和高效

循环链表:比较常规的思路,符合常规的思维

0 0
原创粉丝点击