使用链表学生信息输入输出
链接:https://ac.nowcoder.com/acm/contest/93965/I链接:https://ac.nowcoder.com/acm/contest/93965/I
来源:牛客网
题目描述
输入若干个学生的信息(学号、姓名、成绩),当输入学号为0时结束,用单向链表组织这些学生信息后,再按顺序输出。
输入描述:
输入多行,直到一行开始输入0结束,每行包括,学号(长度小于等于9),姓名(长度小于等于100),成绩,空格分隔。
输出描述:
按照输入顺序输出每位学生信息,一行一个学生信息,学号,姓名,成绩,空格分隔。
示例1
输入
复制
1 linchengda 92
2 chenjiatai 88
3 caoyuxuan 90
4 limengqing 86
0
输出
复制
1 linchengda 92
2 chenjiatai 88
3 caoyuxuan 90
4 limengqing 86
#include <iostream>
#include <string>
using namespace std;
struct Student {
string id;
string name;
int score;
Student* next; };结构体
int main() {
Student* head = nullptr;
Student* tail = nullptr;
链表
while (true) {
string id;
cin >> id;
if (id == "0") {
break;
}
string name;
int score;
cin >> name >> score;
Student* newStudent = new Student();
newStudent->id = id;
newStudent->name = name;
newStudent->score = score;
newStudent->next = nullptr;指向下一个结构体
if (head == nullptr) {
head = newStudent;
tail = newStudent;
} else {
tail->next = newStudent;
tail = newStudent;
}
}
Student* current = head;
while (current != nullptr) {
cout << current->id << " " << current->name << " " << current->score << endl;
current = current->next;
}
current = head;
while (current != nullptr) {
Student* temp = current;
current = current->next;
delete temp;
}
return 0;
}