使用链表学生信息输入输出
#include <iostream>
#include <cstring>
using namespace std;
struct Student {
char id[10];
char name[101];
int score;
Student* next;
};
int main() {
Student* head = nullptr;
Student* tail = nullptr;
while (true) {
Student* s = new Student;
cin >> s->id;
if (strcmp(s->id, "0") == 0) {
delete s;
break;
}
cin >> s->name >> s->score;
s->next = nullptr;
if (head == nullptr) {
head = s;
tail = s;
} else {
tail->next = s;
tail = s;
}
}
Student* current = head;
while (current!= nullptr) {
cout << current->id << " " << current->name << " " << current->score << endl;
Student* nextNode = current->next;
delete current;
current = nextNode;
}
return 0;
}
在 main
函数开始处,定义了两个指针 head
和 tail
,它们都初始化为 nullptr
,分别用于指向链表的头节点和尾节点。初始时链表为空,所以都指向空地址。
- 首先,让指针
current
指向链表的头节点(current = head;
),然后进入循环,只要current
不为空指针,就执行循环体内容。 - 在循环体中,先通过
cout << current->id << " " << current->name << " " << current->score << endl;
输出当前节点所存储的学生学号、姓名和成绩信息。 - 接着,保存当前节点的下一个节点指针到
nextNode
变量(Student* nextNode = current->next;
),这是为了在释放当前节点内存后还能找到后续节点。 - 然后,使用
delete current;
释放当前节点所占用的内存空间,最后将current
指针更新为下一个节点(current = nextNode;
),继续下一轮循环,直到遍历完整个链表,所有节点内存都被释放,current
变为nullptr
时循环结束。