约瑟夫双向生死游戏c语言
时间: 2023-12-25 22:30:34 浏览: 85
以下是C语言实现约瑟夫双向生死游戏的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
struct Node* prev;
} Node;
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
newNode->prev = NULL;
return newNode;
}
void insertNode(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
(*head)->next = *head;
(*head)->prev = *head;
} else {
Node* last = (*head)->prev;
newNode->next = *head;
newNode->prev = last;
last->next = newNode;
(*head)->prev = newNode;
}
}
void deleteNode(Node** head, Node* node) {
if (*head == NULL || node == NULL) {
return;
}
if (*head == node) {
*head = node->next;
}
if (node->next != NULL) {
node->next->prev = node->prev;
}
if (node->prev != NULL) {
node->prev->next = node->next;
}
free(node);
}
void josephusGame(int n, int m) {
Node* head = NULL;
for (int i = 1; i <= n; i++) {
insertNode(&head, i);
}
Node* current = head;
while (n > 15) {
for (int i = 1; i < m; i++) {
current = current->next;
}
Node* next = current->next;
deleteNode(&head, current);
current = next;
n--;
}
printf("Positions to be thrown into the sea: ");
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
int n = 30; // 旅客总数
int m = 9; // 正向计数
int k = 5; // 反向计数
josephusGame(n, m);
return 0;
}
```
阅读全文