使用链表学生信息输入输出

#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 时循环结束。
全部评论

相关推荐

积极的小学生不要香菜:你才沟通多少,没500不要说难
点赞 评论 收藏
分享
07-09 18:28
门头沟学院 Java
写着提前批,结果还要实习4个月以上???
程序员牛肉:这种不用看,直接投了,面试的时候问对应的HR就行。有可能他们是直接复制的暑期实习的模板。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务