首页 > 解决方案 > 通过单链表和两类查找最小和最大数

问题描述

我通过单链表从用户那里获得了几个数字,我的程序的任务是通过两个类在链表中找到最小和最大的数字并将它们打印在屏幕上。但是过了一段时间,我的程序关闭了,我什么也没看到。什么地方出了错?

#include<iostream>
using namespace std;

struct Node
{
    double Number;
    struct Node *Point;

} *End = nullptr;
typedef struct Node node;

namespace Min_Max
{
    class Min
    {
        node *Result = End;

        public: Min()
        {
            if(Result == nullptr)
            {
                cout << "You didn\'t enter anything!\a";
                system("pause");

                exit(EXIT_FAILURE);
            }

            node *Counter = Result->Point;

            while(Counter != nullptr)
            {
                if(Counter->Number < Result->Number)
                    Result = Counter;

                Result = Result->Point;
            }
        }

        node* Show()
        {
            return Result;
        }
};

class Max
{
    private:
        node *Result = End;

    public: 
        Max()
        {
            if(Result == nullptr)
            {
                cout << "You didn\'t enter anything!\a";
                system("pause");

                exit(EXIT_FAILURE);
            }

            node *Counter = Result->Point;

            while(Counter != nullptr)
            {
                if(Counter->Number > Result->Number)
                    Result = Counter;

                Result = Result->Point;
            }
        }

        node* Show()
        {
            return Result;
        }
    };
};

int main()
{
    node *linker = nullptr;
    register short int Counter = 1;

    while(1)
    {
        linker = new node;
        if(linker == nullptr)
        {
            cout << "An error occurred during allocating memory." << endl << endl;
            system("pause");

            return 0;
        }

        cout << "Number " << Counter << ": Enter your number: ";
        cin >> linker->Number;
        system("cls");

        if(linker->Number == 0)
        {
            delete linker;
            break;
        }

        linker->Point = End;
        End = linker;

        Counter++;
    }

    Min_Max::Min Min;
    Min_Max::Max Max;

    cout << "The smallest number is " << (Min.Show())->Number << endl;
    cout << "The largest number is " << (Max.Show())->Number << endl;

    return 0;
}

我的 C++ 编译器是 GCC-C++11,我的操作系统是 Windows 10。

标签: classc++11linked-list

解决方案


推荐阅读