题目描述
输入若干个学生的信息(学号、姓名、成绩),当输入学号为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
方法1:
#include <iostream>
#include <string>
using namespace std;
struct Student {
string id;
string name;
int score;
Student* next;
};
Student* createLinkedList() {
Student* head = new Student;
head->next = nullptr;
Student* p = head;
while (true) {
Student* newNode = new Student;
cin >> newNode->id;
if (newNode->id == "0") {
delete newNode;
break;
}
cin >> newNode->name >> newNode->score;
newNode->next = nullptr;
p->next = newNode;
p = p->next;
}
return head;
}
void printLinkedList(Student* head) {
Student* p = head->next;
while (p != nullptr) {
cout << p->id << " " << p->name << " " << p->score << endl;
p = p->next;
}
}
int main() {
Student* head = createLinkedList();
printLinkedList(head);
return 0;
}
方法2:
#include <iostream>
#include <string>
using namespace std;
// 定义学生信息结构体
struct Student {
string id;
string name;
float score;
Student* next;
};
int main() {
// 头指针和当前节点指针
Student* head = nullptr;
Student* current = nullptr;
// 循环输入学生信息
while (true) {
string id;
string name;
float score;
cin >> id;
// 输入学号为0时结束循环
if (id == "0") {
break;
}
cin >> name >> score;
// 创建新节点
Student* newStudent = new Student{ id, name, score, nullptr };
// 如果链表为空,设置头指针为新节点
if (head == nullptr) {
head = newStudent;
current = newStudent;
} else {
// 否则将新节点链接到当前节点的后面,并更新当前节点指针
current->next = newStudent;
current = newStudent;
}
}
// 输出学生信息
current = head;
while (current != nullptr) {
cout << current->id << " " << current->name << " " << current->score << endl;
current = current->next;
}
// 释放链表内存
current = head;
while (current != nullptr) {
Student* nextStudent = current->next;
delete current;
current = nextStudent;
}
return 0;
}