首页 > 其他 > 详细

约瑟夫问题--循环链表解决方案

时间:2020-08-10 22:33:47      阅读:93      评论:0      收藏:0      [点我收藏+]
//头文件circlelist.h
#pragma once
#ifndef CIRCLELIST_H_
#define CIRCLELIST_H_
#include<iostream>
using namespace std;
struct circleNode{
    float data;
    circleNode* next;
};
class circleList {
private:
    int size;
    circleNode* first;
    circleNode* last;
public:
    circleList(circleNode* newlist=NULL) {
        first = newlist;
    };
    //循环链表的实现方法
    bool insert(float a,int i);//插入,a为插入的数,i为插入的位置。
    bool remove(int i);//删除第i个位置的节点
    circleNode* findPtr(int i);//返回第i个结点的地址
};
#endif // !CIRCLELIST_H_
//源文件circlelist.cpp
#include"circlelink.h"
bool circleList::insert(float a, int x) {
    circleNode* newlist = new circleNode;
    if (newlist == NULL) { cerr << "内存分配错误!" << endl; return false; };
    newlist->data = a;
    if (first == NULL) {
        this->first = newlist;
        newlist->next = first;
        last = newlist;
        size = 1;
    }
    else {
        last->next = newlist;
        newlist->next = first;
        last = newlist;
        size++;
    }
    return true;
}
bool circleList::remove(int i) {
    if (i > size || first == NULL||i<1) {
        cerr << "空表或位置错误!" << endl;
        return false;
    }
    else {
        circleNode* current = first;
        if (i>1) {
            current=this->findPtr(i-1);
            //current指向i-1。
            circleNode* del=current->next;
            if (del == last) {
                last = current;
            }
            current->next = del->next;
            delete del;
            size--;
            return true;
        }else {
            circleNode* n = first->next;
            delete first;
            first = n;
        }
        
        
    }
}
circleNode* circleList::findPtr(int i) {
    circleNode* current = first;
    if (i > size || first == NULL||i<=0) {
        cerr << "未找到元素!" << endl;
    }else {
        for (int j = 1; j < i; j++) {
            current = current->next;
        }
        return current;
    }
    
}
//主文件
#include <iostream>
#include"circlelink.h"
//约瑟夫问题,n--总人数,s---起始位置,m--第几个淘汰
bool josephus(circleList* list,int n,int s,int m) {
    circleNode* current = list->findPtr(s);
    circleNode* pre=NULL;
    if (m <= 0) {
        cerr << "输入有误!" << endl;
        return false;
    }
    for(int x=0;x<n-1;x++){
        for (int j = 1; j < m; j++) {
            pre = current;
            current = current->next;
        }
        cout << current->data << "淘汰了!" << endl; 
        pre->next = current->next;
        delete current;
        current = pre->next;
    }    
    return true;
}
int main()
{
    circleList list;
    for (int i = 1; i < 10; i++) {
        list.insert(i,i);
    }
    josephus(&list,9,1,10);
}

 

约瑟夫问题--循环链表解决方案

原文:https://www.cnblogs.com/my-new-blog-zxj/p/13472430.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!