结构体链条

#include<iostream>

#include<string>

using namespace std;

struct Student {

string id;

string name;

int score;

};

struct Node {

Student student;

Node* next;

};

void insert(Node*& head, const Student& student) {

Node* newNode = new Node;

newNode->student = student;

newNode->next = nullptr;

if (head == nullptr) {

head = newNode;

} else {

Node* temp = head;

while (temp->next!= nullptr) {

temp = temp->next;

}

temp->next = newNode;

}

}

void printList(Node* head) {

Node* temp = head;

while (temp!= nullptr) {

cout << temp->student.id << " " << temp->student.name << " " << temp->student.score << endl;

temp = temp->next;

}

}

int main() {

Node* head = nullptr;

while (true) {

Student student;

cin >> student.id;

if (student.id == "0") {

break;

}

cin >> student.name >> student.score;

insert(head, student);

}

printList(head);

return 0;

}

函数解释: insert(Node*& head, const Student& student): 该函数用于将一个新的学生节点插入到链表中。 首先,创建一个新的 Node 节点 newNode,将传入的 student 信息存储到该节点中,并将其 next 指针初始化为 nullptr。 然后判断链表是否为空(即 head == nullptr),如果为空,则将 head 指针指向新创建的节点。 如果链表不为空,使用 temp 指针从 head 开始遍历链表,直到找到最后一个节点(即 temp->next == nullptr),将新节点添加到该节点的 next 位置。 printList(Node* head): 该函数用于打印链表中的所有学生信息。 从 head 节点开始,使用 temp 指针遍历链表,将每个节点中的学生 id、name 和 score 信息输出到控制台,然后将 temp 指针移向下一个节点,直到 temp 为 nullptr。

全部评论

相关推荐

自学java狠狠赚一...:骗你点star的,港卵公司,记得把star收回去
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 11:16
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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