(五)约瑟夫环问题

来源:互联网 发布:谱子扫描软件 编辑:程序博客网 时间:2024/04/29 16:04
 一:理论
1.约瑟夫环问题的改进:
 一桌人围着圆桌吃饭,只要数到N(比如N=3)的就离开桌子,然后余下的最后一人可以得到大奖。
2.用的数据结构是:循环链表
3.思考:
a.使用与现实问题相近的结构,来解决问题
b.分析 ‘约瑟夫环问题’的时间复杂度
c.以后可以尝试用别的方法比如说数组来解决约瑟夫环问题
二:代码:
#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; //从链表中删除第step个节点
            if ( eliminated_node == tail)
                tail = p;
            std::cout << "deleting:" << eliminated_node->payload << "\n" << 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);
    return 0;

}


0 0
原创粉丝点击