BUPT-homework/semester2/pset1/4-Joseph.c

103 lines
1.9 KiB
C
Raw Normal View History

2022-03-08 20:36:51 +08:00
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
// Clockwise order
struct Node *next;
// Anti clockwise order
struct Node *prev;
// Starts from 1, clockwise
int id;
} Node;
Node *constructRing(int len);
Node *appendNode(Node *head, int id);
Node *deleteNode(Node *head, int direction);
Node *iterateNode(Node *head, int direction,
int count); // 1: clockwise, 0: anti clockwise
int main(void) {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
Node *head = constructRing(n);
int count = 0;
for (int i = 0; i < n; i++) {
// determine the count
if (i % 2 == 0) { // Anti clockwise
count = m;
} else {
count = k;
}
head = iterateNode(head, i % 2, count);
printf("%d ", head->id);
head = deleteNode(head, i % 2);
}
return 0;
}
Node *constructRing(int len) {
// Construct the first node
Node *head = malloc(sizeof(Node));
head->id = 1;
head->prev = NULL;
head->next = NULL;
Node *ptr = head;
for (int i = 2; i <= len; i++) {
ptr = appendNode(ptr, i);
}
ptr->next = head;
head->prev = ptr;
return head;
}
Node *appendNode(Node *head, int id) {
Node *new = malloc(sizeof(Node));
new->id = id;
new->prev = head;
new->next = NULL; // Can be deleted
head->next = new;
return new;
}
Node *deleteNode(Node *head, int direction) {
Node *prev = head->prev;
Node *next = head->next;
if (head == next) {// Single element in the ring
free(head);
return NULL;
}
prev->next = next;
next->prev = prev;
free(head);
if (direction == 1)
return next;
else
return prev;
}
Node *iterateNode(Node *head, int direction,
int count) { // 1: clockwise, 0: anti clockwise
Node *ptr = head;
for (int i = 1; i < count; i++) { // starts from 1
if (direction == 1)
ptr = ptr->next;
else
ptr = ptr->prev;
}
return ptr;
}