用c语言写一个约瑟夫环
时间: 2023-03-29 14:00:36 浏览: 118
C语言编写的约瑟夫环
5星 · 资源好评率100%
好的,我可以回答这个问题。约瑟夫环是一个经典的问题,可以用循环链表来实现。具体实现方法可以参考以下代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *createList(int n) {
Node *head = (Node *)malloc(sizeof(Node));
head->data = 1;
head->next = NULL;
Node *tail = head;
for (int i = 2; i <= n; i++) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = i;
newNode->next = NULL;
tail->next = newNode;
tail = newNode;
}
tail->next = head;
return head;
}
void josephus(int n, int m) {
Node *head = createList(n);
Node *p = head;
while (p->next != p) {
for (int i = 1; i < m - 1; i++) {
p = p->next;
}
printf("%d ", p->next->data);
Node *temp = p->next;
p->next = temp->next;
free(temp);
p = p->next;
}
printf("%d\n", p->data);
free(p);
}
int main() {
int n, m;
printf("请输入总人数n和报数m:");
scanf("%d%d", &n, &m);
josephus(n, m);
return ;
}
```
这个程序可以根据输入的总人数n和报数m,输出约瑟夫环的出队顺序。
阅读全文