圆桌问题(C++)

描述

在这里插入图片描述

代码(C++)

#include <iostream>

using namespace std;

struct person {
    int num;
    person *next;
};


void show(person *first) {
    for (int i = 0; i < 30; ++i) {
        cout << first->num << " ";
        first = first->next;
    }
    cout << endl;
}

int main() {

    int n;
    cin >> n;

    person *first = (person *) malloc(sizeof(person));

    first->next = NULL;

    person *last = first;
    person *p;
    for (int i = 1; i <= n; ++i) {
        p = (person *) malloc(sizeof(person));
        p->num = i;
        last->next = p;
        last = p;
    }


    first = first->next;
    last->next = first;
    int flag = 1;
    person *temp;
    person *trial = first;
//    show(first);

    while (trial->next != trial) {

        if (flag == 3) {
            flag = 1;
            temp = trial->next;
            trial->num = temp->num;
            trial->next = temp->next;
            free(temp);

        } else {
            ++flag;
            trial = trial->next;
        }

    }

    cout << trial->num;

    return 0;
}

结果

在这里插入图片描述

©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页