|
发表于 2023-10-20 16:39:17
|
显示全部楼层
任务描述:
你需要实现一个名为RemoveMin的成员函数,用于删除链表中值最小的元素,并返回该最小元素的值。然后,将给定数组a[10] = {1, 2, 3, 9, 5, 6, 7, 8, 9, 0}中的元素输入到链表容器中,并删除链表中的值最小的元素,并输出容器中剩余的全部元素。
代码实现:
首先,我们需要编写头文件List.h来定义链表容器和相关操作。以下是List.h的代码:
- #pragma once
- template <typename T>
- class List {
- private:
- struct Node {
- T data;
- Node* next;
- Node(const T& d, Node* n = nullptr) : data(d), next(n) {}
- };
- Node* head;
- public:
- List() : head(nullptr) {}
- ~List();
- // 将元素插入链表
- void Insert(const T& value);
-
- // 删除链表中值最小的元素,返回最小元素的值
- T& RemoveMin();
- // 在控制台输出链表元素
- void Print() const;
- };
- // 实现代码需要放在头文件中
复制代码
接下来,我们需要实现List类的成员函数。以下是相关函数的代码实现:
- #include <iostream>
- #include "List.h"
- template <typename T>
- List<T>::~List() {
- Node* current = head;
- while (current != nullptr) {
- Node* temp = current;
- current = current->next;
- delete temp;
- }
- }
- template <typename T>
- void List<T>::Insert(const T& value) {
- if (head == nullptr) {
- head = new Node(value);
- } else {
- Node* current = head;
- while (current->next != nullptr) {
- current = current->next;
- }
- current->next = new Node(value);
- }
- }
- template <typename T>
- T& List<T>::RemoveMin() {
- if (head == nullptr) {
- throw std::runtime_error("链表为空!");
- }
- Node* current = head;
- Node* previous = nullptr;
- Node* minNode = head;
- Node* prevMinNode = nullptr;
- while (current != nullptr) {
- if (current->data < minNode->data) {
- minNode = current;
- prevMinNode = previous;
- }
- previous = current;
- current = current->next;
- }
- if (prevMinNode == nullptr) {
- head = minNode->next;
- } else {
- prevMinNode->next = minNode->next;
- }
- T& minValue = minNode->data;
- delete minNode;
- return minValue;
- }
- template <typename T>
- void List<T>::Print() const {
- Node* current = head;
- while (current != nullptr) {
- std::cout << current->data << " ";
- current = current->next;
- }
- std::cout << std::endl;
- }
复制代码
在主函数中,我们可以使用List类来完成给定任务。以下是实现上述任务的完整代码:
- #include <iostream>
- #include "List.h"
- int main() {
- int a[10] = {1, 2, 3, 9, 5, 6, 7, 8, 9, 0};
- List<int> myList;
- // 将数组元素插入链表容器
- for (int i = 0; i < 10; i++) {
- myList.Insert(a[i]);
- }
- std::cout << "容器中的元素(插入前):";
- myList.Print();
- // 删除链表中的最小元素
- int minValue = myList.RemoveMin();
- std::cout << "删除的最小元素:" << minValue << std::endl;
- std::cout << "容器中的元素(删除后):";
- myList.Print();
- return 0;
- }
复制代码
代码说明:
在上面的代码中,我们首先定义了头文件List.h,其中包含List类和相关成员函数的声明。然后,在cpp文件中,我们根据头文件的定义,实现了List类的成员函数。
在主函数中,我们创建了一个整型数组a,并将其元素插入到List类型的对象myList中。然后,我们输出容器中的元素(插入前)。
接下来,我们调用RemoveMin函数来删除链表中的最小元素,并将最小元素的值打印出来。最后,我们再次输出容器中的元素(删除后)。
希望这段代码对你有所帮助!如果还有其他问题,请随时提问。
球一个最佳答案谢谢啦!这对我非常重要!   |
|