13个人围成一圈,从第1个人开始顺序报号1、2、3,凡报到3的人退出圈子。找出最后留在圈子里的人原来的序号。要求用结构体编程实现。 输出提示 "出圈成员及顺序:" 格式 "%3d" 输出提示 "\n最后的成员是:" 格式 "%3d" 程序的运行示例如下: 出圈成员及顺序:3 6 (后面以此类推,抱歉这里的输出结果保密,暂不公开,注意最后一个人是不出圈的哦) 最后的成员是:(抱歉这里的输出结果保密,暂不公开) C语言代码
时间: 2024-02-03 11:12:15 浏览: 26
下面是一个简单的基于结构体的实现:
```C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int num;
struct Node *next;
};
int main() {
int n, count = 0, m = 3;
printf("请输入总人数:");
scanf("%d", &n);
struct Node *head = (struct Node *) malloc(sizeof(struct Node));
head->num = 1;
head->next = NULL;
struct Node *tail = head;
for (int i = 2; i <= n; i++) {
struct Node *newNode = (struct Node *) malloc(sizeof(struct Node));
newNode->num = i;
newNode->next = NULL;
tail->next = newNode;
tail = newNode;
}
tail->next = head;
struct Node *p = head, *prev = NULL;
while (p->next != p) {
count++;
if (count == m) {
printf("%3d", p->num);
prev->next = p->next;
free(p);
p = prev->next;
count = 0;
} else {
prev = p;
p = p->next;
}
}
printf("%3d\n", p->num);
printf("最后的成员是:%3d\n", p->num);
return 0;
}
```
首先通过循环创建一个循环链表,链表的长度为输入的人数。接着,从头结点开始遍历链表,每报到3就将该结点删除,直到链表中只剩下一个结点为止。最后输出剩下的那个结点的编号,即为最后留在圈子里的人的序号。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)