已知链表节点信息为学号、姓名、课程成绩。现有两个链表分别包含三个节点。编程实现两个链表的合并然后输出。
时间: 2024-05-04 21:21:19 浏览: 114
假设每个节点都是一个 struct 类型,包含三个字段:`int id 表示学号,`string name` 表示姓名,`double score` 表示课程成绩。现在有两个链表分别为 `list1` 和 `list2`,我们需要将它们合并成一个新的链表 `mergedList`,然后输出所有节点的信息。可以按照以下步骤实现。
1. 定义一个新的链表 `mergedList`,并将其初始化为空链表。
2. 遍历 `list1`,将其中的每个节点插入到 `mergedList` 的尾部。
3. 遍历 `list2`,将其中的每个节点插入到 `mergedList` 的尾部。
4. 遍历 `mergedList`,输出其中每个节点的信息。
下面是具体的实现代码(假设 `Node` 是链表节点的结构体):
```c++
#include <iostream>
#include <string>
#include <list>
using namespace std;
struct Node {
int id;
string name;
double score;
};
int main() {
list<Node> list1 = {{1, "Tom", 80}, {2, "Jerry", 90}, {3, "Alice", 85}};
list<Node> list2 = {{4, "Bob", 95}, {5, "Mike", 92}, {6, "Lucy", 88}};
list<Node> mergedList;
// 将 list1 中的节点插入到 mergedList 的尾部
for (auto it = list1.begin(); it != list1.end(); ++it) {
mergedList.push_back(*it);
}
// 将 list2 中的节点插入到 mergedList 的尾部
for (auto it = list2.begin(); it != list2.end(); ++it) {
mergedList.push_back(*it);
}
// 输出 mergedList 中所有节点的信息
for (auto it = mergedList.begin(); it != mergedList.end(); ++it) {
cout << "id: " << it->id << ", name: " << it->name << ", score: " << it->score << endl;
}
return 0;
}
```
输出结果如下:
```
id: 1, name: Tom, score: 80
id: 2, name: Jerry, score: 90
id: 3, name: Alice, score: 85
id: 4, name: Bob, score: 95
id: 5, name: Mike, score: 92
id: 6, name: Lucy, score: 88
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.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/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)