首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

我已经做了一个程序来显示学生的姓名和身高在C++中使用队列链表,现在我想以降序显示它,我不知道如何

在C++中使用队列链表来显示学生的姓名和身高,并以降序显示,可以按照以下步骤进行操作:

  1. 创建一个学生类,包含姓名和身高两个属性。
  2. 创建一个队列链表类,用于存储学生对象。
  3. 在队列链表类中实现插入操作,将学生对象按照身高降序插入队列链表中。
  4. 在队列链表类中实现显示操作,按照降序遍历队列链表,依次输出学生的姓名和身高。
  5. 在主函数中,创建队列链表对象,并添加学生对象。
  6. 调用队列链表对象的显示操作,即可以降序显示学生的姓名和身高。

以下是示例代码:

代码语言:txt
复制
#include <iostream>
#include <string>

using namespace std;

// 学生类
class Student {
public:
    string name;
    int height;

    Student(string n, int h) {
        name = n;
        height = h;
    }
};

// 队列链表类
class QueueLinkedList {
private:
    struct Node {
        Student student;
        Node* next;
    };

    Node* front;
    Node* rear;

public:
    QueueLinkedList() {
        front = nullptr;
        rear = nullptr;
    }

    // 插入操作(按照身高降序插入)
    void insert(Student student) {
        Node* newNode = new Node;
        newNode->student = student;
        newNode->next = nullptr;

        if (front == nullptr) {
            front = newNode;
            rear = newNode;
        } else {
            Node* current = front;
            Node* previous = nullptr;

            while (current != nullptr && current->student.height >= newNode->student.height) {
                previous = current;
                current = current->next;
            }

            if (previous == nullptr) {
                newNode->next = front;
                front = newNode;
            } else {
                previous->next = newNode;
                newNode->next = current;
            }

            if (current == nullptr) {
                rear = newNode;
            }
        }
    }

    // 显示操作(按照降序显示)
    void display() {
        Node* current = front;

        while (current != nullptr) {
            cout << "姓名:" << current->student.name << ",身高:" << current->student.height << endl;
            current = current->next;
        }
    }
};

int main() {
    QueueLinkedList queue;

    // 添加学生对象
    queue.insert(Student("张三", 180));
    queue.insert(Student("李四", 175));
    queue.insert(Student("王五", 185));

    // 以降序显示学生的姓名和身高
    queue.display();

    return 0;
}

以上代码实现了一个使用队列链表在C++中显示学生姓名和身高,并以降序显示的程序。你可以根据实际需求进行修改和扩展。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券