2.3 循环链表和约瑟夫问题

CircLinkList.h

#pragma once
#include<iostream>
using namespace std;

class LNode {
    friend class CircLinkList;
private:
    int data;
    LNode* next;
};

class CircLinkList {
private:
    LNode* first;
    LNode* last;
public:
    CircLinkList() {
        first = new LNode;
        first->data = 666;
        first->next = nullptr;
    }
    void Creat(int arr[],int n) {
        LNode* s;
        LNode* p;
        p = first;
        for (int i = 0; i < n; i++) {
            s = new LNode;
            s->data = arr[i];
            p->next = s;
            p = s;
        }
        last = p;
        last->next = first->next;
    }
    void show() {
        LNode* p;
        p = first->next;
        while (p != last) {
            cout << p->data << " ";
            p = p->next;
        }
        cout << last->data;
        putchar('\n');
    }
    void J(int n, int m) {
        LNode* p;
        p = first;
        for (int i = 0; i < n-1; i++) {
            for (int j = 0; j < m-1; j++) {
                p = p->next;
                
            }
            cout << "remove:" << p->next->data << endl;
            p->next = p->next->next;
        }
        cout << endl;
        cout << "Residue:" << p->data << endl;
    }
};

main:

#include"CircLinkList.h"
int main() {
    CircLinkList L;
    int a[] = { 1,2,3,4,5,6,7,8 };
    L.Creat(a, 8);
    L.show();
    L.J(8, 3);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/SlowIsFast/p/12460478.html
2.3