OOP 将堆栈类设计成一个类模板

177 阅读1分钟

3. 将堆栈类设计成一个类模板,要求堆栈应该包含有常用的堆栈操作(初始化、弹栈、压 栈、取栈顶、清空、判空);并用设计的堆栈类模板生成两个堆栈对象,分别用于 int 和 double 的存取,要求有这两个堆栈的存取代码。

代码:
#include <iostream>
#include <string>
const int maxsize = 100 ;
using namespace std;
template<class T>
class Stack
{
private:
    T arr[maxsize];
    int currentSize;
public:
    Stack() :currentSize(0) {}
    void push(T temp)
    {
        arr[currentSize++] = temp;
    }
    T pop()
    {
        T temp = arr[currentSize - 1];
        arr[currentSize - 1] = NULL;
        currentSize--;
        return temp;
    }
    bool empty()
    {
        return (currentSize == 0) ? true : false;
    }
    bool full()
    {
        return (currentSize == 100) ? true : false;
    }
    int size()
    {
        return currentSize;
    }
    int top()
    {
        return currentSize;
    }
};
int main()
{
    string type = "";
    int length, tempInt, n;
    double tempDouble;
    char tempChar;
    while (cin >> type && type != "STOP")
    {
        cin >> length;
        if (type == "Int")
        {
            Stack<int> Int;
            for (int i = 0; i < length; i++)
            {
                cin >> tempInt;
                if (Int.full()) 
                    cout << "full!! ";
                else Int.push(tempInt);
            }
            cin >> n;
            for (int i = 0; i < n; i++)
            {
                if (!Int.empty())
                    cout << Int.pop();
                else 
                    cout << "empty!!";
                cout << ((i != n - 1) ? " " : "\n");
            }
        }

        else if (type == "Double")
        {
            Stack<double> Double;
            for (int i = 0; i < length; i++)
            {
                cin >> tempDouble;
                if (Double.full()) 
                    cout << "full!! ";
                Double.push(tempDouble);
            }
            cin >> n;
            for (int i = 0; i < n; i++)
            {
                if (!Double.empty())
                    cout << Double.pop();
                else 
                    cout << "empty!!";
                cout << ((i != n - 1) ? " " : "\n");
            }
        }

        else if (type == "Char")
        {
            Stack<char> Char;
            for (int i = 0; i < length; i++)
            {
                cin >> tempChar;
                if (Char.full()) 
                    cout << "full!! ";
                Char.push(tempChar);
            }
            cin >> n;
            for (int i = 0; i < n; i++)
            {
                if (!Char.empty())
                    cout << Char.pop();
                else 
                    cout << "empty!!";
                cout << ((i != n - 1) ? " " : "\n");
            }
        }
    }
    system("PAUSE");
    return 0;
}
运行结果:

3.png