#include <stdio.h>#include <stdlib.h>typedef struct Node { int num; struct Node *next;} Node;void createList(Node **head, int n) { Node *p, *prev; *head = (Node *)malloc(sizeof(Node)); (*head)->num = 1; prev = *head; for (int i = 2; i <= n; i++) { p = (Node *)malloc(sizeof(Node)); p->num = i; prev->next = p; prev = p; } prev->next = *head;}void josephu(int n, int m, int k) { Node *head, *prev, *p; createList(&head, n); prev = head; while (prev->next != head) { prev = prev->next; } p = head; for (int i = 1; i < k; i++) { prev = p; p = p->next; } while (p->next != p) { for (int i = 1; i < m; i++) { prev = p; p = p->next; } printf("%d ", p->num); prev->next = p->next; free(p); p = prev->next; } printf("%d\n", p->num); free(p);}int main() { int n = 8, m = 4, k = 3; josephu(n, m, k); return 0;}添加注释
时间: 2023-06-19 16:09:38 浏览: 117
#include <stdio.h>
#include <stdlib.h>
typedef struct Node { //定义结构体Node
int num; //节点编号
struct Node *next; //指向下一个节点的指针
} Node;
void createList(Node **head, int n) { //创建循环链表
Node *p, *prev;
*head = (Node *)malloc(sizeof(Node)); //创建头节点
(*head)->num = 1; //头节点编号为1
prev = *head;
for (int i = 2; i <= n; i++) { //依次创建其他节点
p = (Node *)malloc(sizeof(Node));
p->num = i;
prev->next = p; //将新节点加入链表
prev = p;
}
prev->next = *head; //将最后一个节点指向头节点,形成循环链表
}
void josephu(int n, int m, int k) { //约瑟夫环问题
Node *head, *prev, *p;
createList(&head, n); //创建循环链表
prev = head;
while (prev->next != head) { //找到链表的最后一个节点
prev = prev->next;
}
p = head;
for (int i = 1; i < k; i++) { //找到从哪个节点开始报数
prev = p;
p = p->next;
}
while (p->next != p) { //循环直到只剩下一个节点
for (int i = 1; i < m; i++) { //报m个数
prev = p;
p = p->next;
}
printf("%d ", p->num); //输出出局的节点编号
prev->next = p->next; //删除出局的节点
free(p);
p = prev->next; //指向下一个节点
}
printf("%d\n", p->num); //输出最后剩下的节点编号
free(p);
}
int main() {
int n = 8, m = 4, k = 3;
josephu(n, m, k); //解决约瑟夫环问题
return 0;
}
阅读全文