链表实现约瑟夫

#include<bits/stdc++.h>
using namespace std;
struct node 
{
    int val;
    node *left,*right;
};
int main()
{
    int n,m;
    cin>>n>>m;
    node *head;
    head=new node;
    head->val=1;
    head->left=head;
    head->right=head;
    
    node *tail=head;
    for(int i=2;i<=n;i++)
    {
        node *p;
        p=new node;
        p->val=i;
        p->left=tail;
        p->right=NULL;
        
        tail->right=p;
        tail=p;
    }
    tail->right=head;
    head->left=tail;
    
    node *now=head;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m-1;j++)
            now=now->right;
        cout<<now->val<<" ";
        
        now->left->right=now->right;
        now->right->left=now->left;
        
        now=now->right;
    }
    return 0;
}

 

posted @ 2019-07-31 19:56  octal_zhihao  阅读(202)  评论(0编辑  收藏  举报