4 solutions

  • 0
    @ 2022-8-6 22:15:00

    这道题是一道经典的循环链表

    #include <bits/stdc++.h>
    
    //循环链表
    
    using namespace std;
    
    const int maxn = 1e3 + 5;
    int id[maxn];
    
    typedef struct Node {
    int value;
    Node *next;
    }NodeList;
    
    int main(void) {
    int n, m;
    cin >> n >> m;
    NodeList *head, *last = NULL;
    NodeList *node;
    
    for (int i = 1; i <= n; i++) {
        node = (NodeList*)malloc(sizeof(NodeList));
        node->value = i;
        if (i == 1) {
            head = node;
            last = node;
        }else {
            last->next = node;
            last = node;
        }
    }
    node->next = head;
    last = node;
    
    int i = 1;
    int cnt = 1;
    while (head->next != head) {
        if (i == m) {
            NodeList *p = head;
            last->next = head->next;
            id[p->value] = cnt;
            cnt ++;
            free(p);
            i = 1;
            head = last->next;
        }else {
            last = head;
            head = head->next;
            i ++;
        }
    }
    
    for (int i = 1; i <= n; i++) {
        if (!id[i]) id[i] = n;
        cout << id[i] << ' ';
    }
    
    return 0;
    

    }

    Information

    ID
    79
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    6
    Tags
    # Submissions
    283
    Accepted
    96
    Uploaded By