码迷,mamicode.com
首页 > 编程语言 > 详细

约瑟夫环问题(c++)

时间:2016-08-20 01:33:20      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

#include <iostream>

struct node{
    int payload;
    node* next;
    node(int payload){this->payload = payload;}
};

class joseph_circle{
    node* tail;
    node* eliminate_ptr;
public:
    joseph_circle(){tail =nullptr;}
    void add(int value){
        if(tail ==nullptr){
            tail= new node(value);
            tail->next = tail;
        }else{
            node* new_node = new node(value);
            new_node->next = tail->next;
            tail->next = new_node;
            tail = new_node;
        }
    }

    void eliminate(int step){
        node* p = tail;
        while(p!=nullptr && p->next!=p){
            for(int i=0;i<step-1;i++){
                p =p->next;
            }
            node* eliminated_node = p->next;
            p->next = p->next->next;
            if(eliminated_node ==tail)
                tail =p;
            std::cout << "deleting:" << eliminated_node->payload << std::endl;
            delete eliminated_node;
            output();  
        }
    }

    void output(){
        node* p = tail;
        while(p != nullptr){
            p=p->next;
            std::cout << p->payload << " ";
            if(p==tail)
                break;
        }
        std::cout << std::endl;
    }
};

int main(){
    joseph_circle circle;
    for(int i=0;i<6;i++){
        circle.add(i);
    }
    circle.eliminate(3);
    system("pause");
    return 0;
}

 

约瑟夫环问题(c++)

标签:

原文地址:http://www.cnblogs.com/zychengzhiit1/p/5789485.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!