【C++】约瑟夫环(数组+链表)

基于数组:

#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;

int *a;
int *vis;

bool isfull(int m)
{
    for(int i=0;i<m;i++)
    {
        if(!vis[i])
            return false;
    }
    return true;
}

void john(int m,int n)
{
    int p=m-1;
    while(!isfull(m))
    {
        int left=n;
        while(left>0)
        {
            p=(p+1)%m;
            if(!vis[p])
            {
                left--;
            }
            cout<<vis[p];
        }
        vis[p]=1;
        cout<<":"<<a[p]<<endl;
    }
}

int main()
{
    int m,n;
    while(scanf("%d %d",&m,&n)&&m&&n)
    {
        a=(int *)malloc(m*sizeof(int));
        for(int i=0;i<m;i++)
            a[i]=i+1;
        vis=(int *)malloc(m*sizeof(int));
        for(int i=0;i<m;i++)
            vis[i]=0;
        
        john(m,n);
    }
    
    return 0;
}

 

基于链表:

#include<iostream>
using namespace std;

struct node
{
    int data;
    node *next;
};

node *head;

void john(int m,int n)
{
    node *p=head;
    node *r=head->next;
    while(r->next!=head)
        r=r->next;
    while(p)
    {
        if(p->next==p)
        {
            cout<<p->data<<endl;
            return ;
        }
        int left=n;
        while(left>1)
        {
            left--;
            p=p->next;
            r=r->next;
        }
        cout<<p->data<<endl;
        r->next=p->next;
        delete p;
        p=r->next;
    }
}

int main()
{
    int m,n;
    while(scanf("%d %d",&m,&n)&&m&&n)
    {
        head=new node();
        head->data=1;
        node *p=head;
        int a=2;
        while(a<=m)
        {
            node *t=new node();
            t->data=a;
            p->next=t;
            p=p->next;
            a++;
        }
        p->next=head;//形成环 
        /*
        p=head->next;
        while(p!=head)
        {
            cout<<p->data<<endl;
            p=p->next;
        }
        */
        john(m,n);
    }
    
    return 0;
}

 

运行示例:

 

 

tz@HZAU

2019/3/12

posted on 2019-03-12 22:16  tuzhuo  阅读(292)  评论(0编辑  收藏  举报