利用动态链表存储图书馆中的学生信息c++
时间: 2024-04-08 07:36:25 浏览: 8
当使用动态链表来存储图书馆中的学生信息时,你可以创建一个学生类,每个实例代表一个学生。然后,你可以创建一个节点类,每个节点包含一个学生实例和指向下一个节点的指针。这样,你可以使用链表来连接所有的学生节点。
下面是一个示例的C++代码,演示了如何使用动态链表存储图书馆中的学生信息:
```cpp
#include <iostream>
#include <string>
using namespace std;
// 学生类
class Student {
public:
string name;
int age;
string major;
Student(string n, int a, string m) : name(n), age(a), major(m) {}
};
// 节点类
class Node {
public:
Student student;
Node* next;
Node(Student s) : student(s), next(nullptr) {}
};
// 图书馆类
class Library {
public:
Node* head;
Library() : head(nullptr) {}
// 添加学生
void addStudent(Student student) {
Node* newNode = new Node(student);
if (head == nullptr) {
head = newNode;
} else {
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
}
}
// 显示所有学生
void displayStudents() {
Node* current = head;
while (current != nullptr) {
cout << "Name: " << current->student.name << endl;
cout << "Age: " << current->student.age << endl;
cout << "Major: " << current->student.major << endl;
cout << endl;
current = current->next;
}
}
};
int main() {
// 创建图书馆对象
Library library;
// 添加学生
Student student1("Alice", 20, "Computer Science");
library.addStudent(student1);
Student student2("Bob", 21, "Mathematics");
library.addStudent(student2);
Student student3("Charlie", 19, "Physics");
library.addStudent(student3);
// 显示所有学生
library.displayStudents();
return 0;
}
```
这个示例代码演示了如何创建学生类、节点类和图书馆类。在主函数中,我们创建了一些学生并将他们添加到图书馆中,然后显示了所有的学生信息。
请注意,在实际应用中,你可能需要添加更多的功能,比如删除学生、搜索学生等。这只是一个简单的示例,供你参考动态链表存储图书馆中学生信息的基本思路。