用链队解决约瑟夫问题 c语言
时间: 2024-01-05 22:03:16 浏览: 25
下面是使用链队解决约瑟夫问题的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
typedef struct Node Node;
Node *createList(int n) {
Node *head = NULL;
Node *tail = NULL;
for (int i = 1; i <= n; i++) {
Node *p = (Node *) malloc(sizeof(Node));
p->data = i;
p->next = NULL;
if (tail == NULL) {
head = tail = p;
} else {
tail->next = p;
tail = p;
}
}
tail->next = head;
return head;
}
void josephus(int n, int k) {
Node *head = createList(n);
Node *p = head;
for (int i = 1; i < k; i++) {
p = p->next;
}
while (n--) {
Node *q = p->next;
if (n == 0) {
printf("%d\n", q->data);
} else {
printf("%d ", q->data);
}
p->next = q->next;
free(q);
p = p->next;
}
}
int main() {
int n, k;
scanf("%d %d", &n, &k);
josephus(n, k);
return 0;
}
```
该算法使用一个循环链表来模拟游戏过程,每次从当前节点的下一个节点开始数k个,然后删除该节点,并将当前节点指向下一个节点,直到只剩一个节点。其中,createList函数用于创建循环链表,josephus函数用于解决约瑟夫问题。