运用循环单链表实现约瑟夫问题c语言代码
时间: 2024-09-27 18:01:03 浏览: 64
约瑟夫环是一个经典的算法问题,通常用于演示递归和模运算的概念。在循环单链表中实现约瑟夫问题,首先需要创建一个节点结构和一个头指针,然后模拟人们从列表中按顺序移除并跳过指定步骤的过程。
以下是一个简单的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}
void josephusProblem(Node* head, int steps) {
if (head == NULL || steps <= 0) {
printf("Invalid input.\n");
return;
}
Node* victim = head;
for (int i = 1; i <= steps - 1; i++) {
victim = victim->next;
}
while (victim != NULL) {
Node* temp = victim->next;
free(victim);
victim = temp;
if (victim == NULL) {
victim = head;
while (victim->next != head) {
victim = victim->next;
}
} else {
for (int i = 1; i < steps; i++) {
victim = victim->next;
}
}
}
}
// 添加节点到链表
void appendToList(Node** head, int value) {
Node* newNode = createNode(value);
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
int main() {
Node* head = NULL;
int n, steps;
printf("Enter the number of people: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
appendToList(&head, i);
}
printf("Enter the step count: ");
scanf("%d", &steps);
josephusProblem(head, steps);
printf("The last person standing is at position %d\n", head->data);
return 0;
}
```
在这个代码里,用户先输入人数和步骤数,然后程序会创建一个循环链表,并应用约瑟夫环算法。`josephusProblem`函数负责执行约瑟夫环的规则,最后输出存活的人及其位置。
阅读全文