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


 

题目描述

输入若干个学生的信息(学号、姓名、成绩),当输入学号为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;
}

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山月@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值