C语言 有n个人围成一圈,顺序排号。从第一人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。 程序的运行示例如下: 请输入人数:30 30个人中最后留下的是第29号
时间: 2023-12-23 08:23:19 浏览: 50
好的,这是一个经典的约瑟夫问题,可以使用循环链表来解决。以下是使用 C 语言编写的程序:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int number;
struct Node* next;
} Node;
Node* createList(int n) {
Node* head = NULL;
Node* prev = NULL;
for (int i = 1; i <= n; i++) {
Node* node = (Node*) malloc(sizeof(Node));
node->number = i;
if (prev != NULL) {
prev->next = node;
}
prev = node;
if (i == 1) {
head = node;
}
}
prev->next = head;
return head;
}
int main() {
int n, count = 0;
printf("请输入人数:");
scanf("%d", &n);
Node* head = createList(n);
Node* current = head;
while (current->next != current) {
count++;
if (count == 3) {
Node* temp = current->next;
current->next = temp->next;
free(temp);
count = 0;
} else {
current = current->next;
}
}
printf("%d个人中最后留下的是第%d号\n", n, current->number);
return 0;
}
```
程序中使用 `createList` 函数创建了一个有 `n` 个节点的循环链表,每个节点的 `number` 属性记录了该节点对应的人的编号。然后从第一个节点开始,不断循环报数,当报到 3 时,删除当前节点,直到链表中只剩一个节点为止,输出该节点对应的人的编号即可。