who is the last?

#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *next;
};

struct node *create_circle(int n) {
    if (n == 0) return NULL;
    struct node *head = (struct node *)malloc(sizeof(struct node));
    head->data = 1;
    head->next = NULL;
    struct node *tail = head;
    for (int i = 2; i <= n; i++) {
        struct node *new_node = (struct node *)malloc(sizeof(struct node));
        new_node->data = i;
        new_node->next = NULL;
        tail->next = new_node;
        tail = new_node;
    }
    tail->next = head;
    return head;
}

int main() {
    int N, M;
    scanf("%d,%d", &N, &M);
    struct node *head = create_circle(N);
    struct node *current = head;
    int num = N;
    int *order = (int *)malloc(N * sizeof(int));
    int idx = 0;
    while (num > 1) {
        struct node *prev = current;
        struct node *temp = current->next;
        int count = 1;
        while (count < M) {
            prev = temp;
            temp = temp->next;
            count++;
        }
        order[idx++] = temp->data;
        prev->next = temp->next;
        free(temp);
        current = prev->next;
        num--;
    }
    if (num == 1) {
        order[idx++] = current->data;
        free(current);
    }
    for (int i = 0; i < N; i++) {
        printf("%d", order[i]);
        if (i < N - 1) printf(",");
    }
    free(order);
    return 0;
}

 

posted @ 2025-12-24 10:01  我不是青山  阅读(2)  评论(0)    收藏  举报