C++编程实现 有 nn 个人排队,11 号排在 22 号前面,22 号排在 33 号前面,...,以此类推 n-1n−1 号排在 nn 号前面。在这个过程中,偶尔老师会把某个人叫走,叫走之后这个人就离开了队伍,假设本来 aa 排在 bb 前面,bb 排在 cc 前面,bb 被叫走后 aa 就排在了 cc 前面。老师偶尔也会感到疑问,她想知道此时排在 aa 号前面的同学是几号呢? 已知老师一共会有 kk 次操作,每次会执行下面的一种: 1.1. 把 xx 叫走。 2.2. 求排在 xx 前面的是谁。
时间: 2023-02-07 19:01:55 浏览: 104
你可以用一个链表来解决这个问题。在链表中,每个节点都代表一个学生,包含两个信息:这个学生的编号和指向下一个学生的指针。
建立这个链表的方法是,先创建一个学生的节点,然后让这个节点的指针指向下一个学生的节点,依次类推。这样,当你想要叫走一个学生的时候,你只需要把他的前一个学生的指针指向他的后一个学生就可以了。查询一个学生前面的学生的时候,你只需要遍历链表,直到找到这个学生为止。
下面是一个简单的 C 代码实现:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct student {
int number;
struct student *next;
} Student;
int main() {
// 建立链表
Student *head = NULL;
for (int i = 1; i <= n; i++) {
Student *new_student = (Student*)malloc(sizeof(Student));
new_student->number = i;
new_student->next = head;
head = new_student;
}
// 叫走一个学生
int x;
scanf("%d", &x);
Student *prev = NULL;
Student *curr = head;
while (curr != NULL) {
if (curr->number == x) {
if (prev == NULL) {
head = curr->next;
} else {
prev->next = curr->next;
}
break;
}
prev = curr;
curr = curr->next;
}
// 查询某个学生前面的学生
int y;
scanf("%d", &y);
curr = head;
while (curr != NULL) {
if (curr->number == y) {
if (
相关推荐
![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)
![](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)