89 lines
1.5 KiB
C
89 lines
1.5 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
typedef struct ListNode {
|
|
int val;
|
|
struct ListNode *next;
|
|
} ListNode;
|
|
|
|
ListNode *appendNode(ListNode *node, int val) {
|
|
ListNode *new = malloc(sizeof(ListNode));
|
|
node->next = new;
|
|
|
|
new->next = NULL;
|
|
new->val = val;
|
|
|
|
return new;
|
|
}
|
|
|
|
void freeNode(ListNode *head) {
|
|
if (head != NULL) {
|
|
ListNode * ptr = head->next;
|
|
free(head);
|
|
freeNode(ptr);
|
|
}
|
|
}
|
|
|
|
void deleteNode(ListNode *node) {
|
|
// deletes node after this one.
|
|
ListNode* tmp = node->next;
|
|
node->next = node->next->next;
|
|
|
|
// printf("Deleted: %d\n", tmp->val);
|
|
|
|
tmp->next = NULL;
|
|
free(tmp);
|
|
}
|
|
|
|
void printNode(ListNode *head) {
|
|
ListNode *ptr = head;
|
|
|
|
while (ptr != NULL) {
|
|
printf("%d->", ptr->val);
|
|
ptr = ptr->next;
|
|
}
|
|
|
|
printf("NULL\n");
|
|
}
|
|
|
|
int main(void) {
|
|
// N people, M passes
|
|
int N, M;
|
|
scanf("%d%d", &M, &N);
|
|
|
|
// construct ring
|
|
ListNode *head = malloc(sizeof(ListNode));
|
|
ListNode *ptr = head;
|
|
|
|
for (int i = 1; i <= N; i++) {
|
|
ptr = appendNode(ptr, i);
|
|
}
|
|
|
|
printNode(head->next);
|
|
// enclose the ring
|
|
ptr->next = head->next;
|
|
|
|
// start simulation
|
|
ListNode** cur = &head;
|
|
ListNode** tmp;
|
|
int pass = 0;
|
|
|
|
while ((*cur) && (*cur)->next && (*cur)->next->next) {
|
|
// printf("Potato: %d\n", (*cur)->next->val);
|
|
if (pass == M) {
|
|
// kick this player, and continue.
|
|
tmp = cur;
|
|
deleteNode(*cur);
|
|
pass = 0;
|
|
} else {
|
|
cur = &(*cur)->next;
|
|
pass++;
|
|
}
|
|
}
|
|
printf("Remaining: %d\n", (*cur)->next->val);
|
|
|
|
free(head);
|
|
free(cur);
|
|
return 0;
|
|
}
|