约瑟夫环

嘿嘿嘿写出来啦!!开心!!!用单循环链表实现的

#include <iostream>
#include <string>

using namespace std;

struct PersonNode  //成员结点
{
    string name;
    int num;
    string sex;
    int age;
    string clas;
    string health;
    PersonNode *next;
    PersonNode(const string& n,const int& numb,const string& s,const int& a,const string& c,const string& h,PersonNode *p=NULL)
    {
        name = n;
        num = numb;
        sex = s;
        age = a;
        clas = c;
        health = h;
        next = p;
    }
    PersonNode(PersonNode *p=NULL)
    {
        next = p;
    }
};

class CirList
{
private:
    PersonNode *first;

public:
    CirList();
    ~CirList();

    void InputRear(const string& name,const int& num,const string& s,const int& a,const string&c,const string& h);  //尾插法形成一个环
    void Process(int m);
    bool IsEmpty();
};

CirList::CirList()
{
    first = NULL;
}

CirList::~CirList()
{

}

void CirList::InputRear(const string& name,const int& num,const string& s,const int& a,const string& c,const string& h)
{
    PersonNode *newN = new PersonNode(name,num,s,a,c,h);
    if(first == NULL)
    {
        first = newN;
        newN->next = first;
        return;
    }

    PersonNode *cur = first;
    while(cur->next != first)
        cur = cur->next;

    cur->next = newN;
    newN->next = first;
}

void CirList::Process(int m)
{
    PersonNode* t = first;
    int f = 0;
    while(1)
    {
        PersonNode* p = t;
        if(p->next == p && f==1)
        {
            cout<<p->name<<' '<<p->num<<' '<<p->sex<<' '<<p->age<<' '<<p->clas<<' '<<p->health<<endl;
            return;
        }
        for(int i=1; i<m-1; i++)
        {
            p = p->next;
            f=1;
        }
        PersonNode* del = p->next;
        cout<<del->name<<' '<<del->num<<' '<<del->sex<<' '<<del->age<<' '<<del->clas<<' '<<del->health<<endl;

        p->next = del->next;
        delete del;
        t = p->next;
    }
}

int main()
{
    int n,m;
    string name;
    int num;
    string sex;
    int age;
    string clas;
    string health;
    CirList lst;

    cin>>n>>m;

    while(n--)
    {
        cin >> name >> num >> sex >> age >> clas >> health;
        lst.InputRear(name,num,sex,age,clas,health);
    }
    lst.Process(m);

    return 0;
}

 

posted @ 2020-10-07 08:21  ananasaa  阅读(125)  评论(0编辑  收藏  举报