学生信息管理系统c++链表
时间: 2023-11-30 22:41:59 浏览: 152
学生信息管理系统可以使用链表来实现,以下是一个使用C++链表实现增加和删除学生信息的示例代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
// 定义学生结构体
struct Student {
string name;
int age;
string gender;
string major;
};
// 定义链表节点结构体
struct Node {
Student data;
Node* next;
};
// 定义链表类
class LinkedList {
public:
LinkedList() {
head = new Node;
head->next = NULL;
}
~LinkedList() {
Node* p = head;
while (p) {
Node* q = p->next;
delete p;
p = q;
}
}
// 在链表末尾添加节点
void addNode(Student stu) {
Node* p = head; while (p->next) {
p = p->next;
}
Node* newNode = new Node;
newNode->data = stu;
newNode->next = NULL;
p->next = newNode;
}
// 删除指定位置的节点
void deleteNode(int index) {
Node* p = head;
int i = 0;
while (p->next && i < index - 1) {
p = p->next;
i++;
}
if (!p->next || i > index - 1) {
cout << "删除位置无效!" << endl;
return;
}
Node* q = p->next;
p->next = q->next;
delete q;
}
// 显示链表中的所有节点
void display() {
Node* p = head->next;
while (p) {
cout << "姓名:" << p->data.name << ",年龄:" << p->data.age << ",性别:" << p->data.gender << ",专业:" << p->data.major << endl;
p = p->next;
}
}
private:
Node* head;
};
// 测试代码
int main() {
LinkedList list;
Student stu1 = {"张三", 20, "男", "计算机科学"};
Student stu2 = {"李四", 21, "女", "软件工程"};
Student stu3 = {"王五", 22, "男", "信息安全"};
list.addNode(stu1);
list.addNode(stu2);
list.addNode(stu3);
list.display();
list.deleteNode(2);
list.display();
return 0;
}
```
阅读全文