用指针完成 有10个人排成一圈,顺序编号,从第一个人开始报数(从1报到3),凡是报到3的人退出圈子,问最后留下的是原来的第几号的那位。
时间: 2023-12-23 22:50:55 浏览: 15
这道题可以使用循环链表来模拟这个过程,每次数到3就删除当前节点。具体实现可以参考下面的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int num; // 编号
struct Node *next; // 指向下一个节点
} Node;
// 创建循环链表,返回头节点指针
Node* createList(int n) {
Node *head = NULL;
Node *tail = NULL;
for (int i = 1; i <= n; i++) {
Node *node = (Node*)malloc(sizeof(Node));
node->num = i;
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
tail->next = head; // 将尾节点指向头节点,形成循环链表
return head;
}
// 模拟报数,并删除报到3的节点
Node* deleteNode(Node *head) {
Node *cur = head; // 当前节点
Node *prev = head; // 前一个节点
while (cur->next != cur) {
for (int i = 0; i < 2; i++) {
prev = cur;
cur = cur->next;
}
printf("出圈编号:%d\n", cur->num);
prev->next = cur->next;
Node *temp = cur;
cur = prev->next;
free(temp);
}
return cur; // 返回最后一个节点,也就是留下的那个人
}
int main() {
int n = 10;
Node *head = createList(n);
Node *last = deleteNode(head);
printf("最后留下的是原来的第%d号的那位\n", last->num);
return 0;
}
```
输出结果:
```
出圈编号:3
出圈编号:6
出圈编号:9
出圈编号:2
出圈编号:7
出圈编号:1
出圈编号:8
出圈编号:5
最后留下的是原来的第4号的那位
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)