C语言实现约瑟夫环问题详解
以下是使用C语言编写的约瑟夫环问题解决方案:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *createList(int n);
void printList(Node *head);
void josephus(int m, Node **head);
int main(void) {
int n, m;
Node *head;
printf("请输入人数n:");
scanf("%d", &n);
printf("请输入报数m:");
scanf("%d", &m);
head = createList(n);
printf("初始队列为:");
printList(head);
josephus(m, &head);
printf("出队顺序为:");
printList(head);
return 0;
}
Node *createList(int n) {
int i;
Node *head = NULL, *tail = NULL, *p;
for (i = 1; i <= n; i++) {
p = (Node *)malloc(sizeof(Node));
p->data = i;
p->next = NULL;
if (head == NULL) {
head = p;
} else {
tail->next = p;
}
tail = p;
}
tail->next = head;
return head;
}
void printList(Node *head) {
Node *p = head;
do {
printf("%d ", p->data);
p = p->next;
} while (p != head);
printf("\n");
}
void josephus(int m, Node **head) {
Node *p, *q;
int i;
while (*head != (*head)->next) {
p = (*head)->next;
q = *head;
for (i = 1; i < m; i++) {
q = p;
p = p->next;
}
q->next = p->next;
printf("%d ", p->data);
free(p);
*head = q->next;
}
}
该程序思路为:
- 创建一个循环链表,链表中每个节点代表一个人,节点数据为该人编号。
- 从链表头开始,每次数m个人出局,直到只剩下一个人为止。
- 每次出局的人打印出来,直到全部人都出局。
程序中使用了结构体来定义链表节点,包括数据和指针域。createList函数用于创建循环链表,printList函数用于打印链表,josephus函数用于求解约瑟环问题。
原文地址: https://www.cveoy.top/t/topic/miKy 著作权归作者所有。请勿转载和采集!