今日题目 + 题解
2024-01-13 11:03:42
发布于:浙江
题目网址:https://www.luogu.com.cn/problem/P1996
标准代码:
#include <iostream>
using namespace std;
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(nullptr) {}
};
void JosephusProblem(int n, int m) {
    ListNode* head = new ListNode(1);
    ListNode* cur = head;
    for (int i = 2; i <= n; i++) {
        cur->next = new ListNode(i);
        cur = cur->next;
    }
    cur->next = head; // 构建循环链表
    while (cur->next != cur) { // 当只剩下一个节点时停止循环
        for (int i = 1; i < m; i++) {
            cur = cur->next; // 移动到下一个节点
        }
        ListNode* temp = cur->next; // 需要删除的节点
        cur->next = temp->next; // 删除节点
        cout << temp->val << " "; // 输出删除节点的编号
        delete temp; // 释放内存
    }
    cout << cur->val; // 输出最后一个节点的编号
    delete cur; // 释放内存
}
int main() {
    int n, m;
    cin >> n >> m;
    JosephusProblem(n, m);
    return 0;
}
以上代码由Chat GPT 3.5生成。
这里空空如也









有帮助,赞一个