C语言链表实现约瑟夫环
时间: 2024-02-02 10:04:05 浏览: 86
C语言实现约瑟夫环
以下是C语言链表实现约瑟夫环的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建循环链表
Node* createCircularLinkedList(int n) {
Node* head = NULL;
Node* prev = NULL;
for (int i = 1; i <= n; i++) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = i;
if (head == NULL) {
head = newNode;
} else {
prev->next = newNode;
}
newNode->next = head;
prev = newNode;
}
return head;
}
// 删除指定位置的节点
Node* deleteNode(Node* head, int position) {
if (head == NULL) {
return NULL;
}
Node* current = head;
Node* prev = NULL;
// 找到要删除的节点
for (int i = 1; i < position; i++) {
prev = current;
current = current->next;
}
// 删除节点
if (prev == NULL) {
prev = current;
while (prev->next != head) {
prev = prev->next;
}
prev->next = current->next;
head = current->next;
} else {
prev->next = current->next;
}
free(current);
return head;
}
// 约瑟夫环问题求解
void josephusCircle(int n, int m) {
Node* head = createCircularLinkedList(n);
Node* current = head;
printf("出列顺序:");
while (n > 0) {
// 找到要删除的节点
for (int i = 1; i < m; i++) {
current = current->next;
}
// 输出出列的节点
printf("%d ", current->data);
// 删除节点
head = deleteNode(head, current->data);
current = current->next;
n--;
}
printf("\n");
}
int main() {
int n, m;
printf("请输入总人数n:");
scanf("%d", &n);
printf("请输入报数m:");
scanf("%d", &m);
josephusCircle(n, m);
return 0;
}
```
阅读全文