BUPT-homework/semester3/pset1/7-4-who-is-the-last.c

85 lines
1.4 KiB
C
Raw Permalink Normal View History

2022-10-08 09:33:48 +08:00
#include <stdio.h>
#include <stdlib.h>
typedef struct listNode {
int id;
struct listNode *next;
int out;
} listNode;
listNode *appendNode(int id, listNode *head) {
listNode *new = malloc(sizeof(listNode));
new->id = id;
new->next = NULL;
new->out = 0;
head->next = new;
return new;
}
listNode *makecircle(const int N) {
listNode *head = malloc(sizeof(listNode));
head->id = 1;
head->next = NULL;
head->out = 0;
listNode *ptr = head;
for (int i = 2; i <= N; i++) {
ptr = appendNode(i, ptr);
// printf("appending: %d\n", i);
}
ptr->next = head;
return head;
}
void printCircle(listNode *head) {
if (head->out == 0) {
printf("%d->", head->id);
}
head = head->next;
while (head->id != 1) {
if (head->out == 0) {
printf("%d->", head->id);
}
head = head->next;
}
printf("|");
}
int main(void) {
int N, M;
scanf("%d,%d", &N, &M);
listNode *head = makecircle(N);
// printCircle(head);
int count = N;
int step = 0;
listNode *ptr = head;
while (count != 0) {
while (step != M) {
while (ptr->out == 1) {
ptr = ptr->next;
}
ptr = ptr->next;
step++;
}
step = 0;
while (ptr->out == 1) {
ptr = ptr->next;
}
ptr->out = 1;
count--;
if (count != 0) {
printf("%d,", ptr->id);
}
}
printf("%d", ptr->id);
return 0;
}