模板类的案例——栈操作

c++头文件:

//头文件mytest.h
#ifndef MYTEST_H_INCLUDED
#define MYTEST_H_INCLUDED

#include <iostream>
//栈模版类
template <typename Type>
class Stack
{
private:
    enum {MAX = 10};
    int stack_top;//stack_top从0取到10,共11个数
    Type items[MAX];
public:
    Stack();
    ~Stack();
    bool push(const Type &);//将数据压栈
    bool pop(Type &);//将数据弹出栈
    void DisplayStackState();//显示栈的状态
    void DisplayStackData();//显示栈中数据
protected:
    bool isempty();//判断栈是否为空
    bool isfull();//判断栈是否已满
};
//成员函数定义
template <typename Type>
Stack<Type>::Stack() : stack_top(0) {}

template <typename Type>
Stack<Type>::~Stack() {}

template <typename Type>
bool Stack<Type>::push(const Type &item)
{
    if(stack_top < MAX)
    {
        items[stack_top] = item;
        ++stack_top;
        if(stack_top > MAX)
            stack_top = MAX;
        return true;
    }
    else
    {
        return false;
    }
}

template <typename Type>
bool Stack<Type>::pop(Type & item)
{
    if(stack_top > 0)
    {
        --stack_top;
        item = items[stack_top];
        if(stack_top < 0)
            stack_top = 0;
        return true;
    }
    else
    {
        return false;
    }
}

template <typename Type>
bool Stack<Type>::isempty()
{
    return stack_top == 0;
}

template <typename Type>
bool Stack<Type>::isfull()
{
    return stack_top == MAX;
}

template <typename Type>
void Stack<Type>::DisplayStackState()
{
    if(isempty())
        std::cout << "栈为空!" << std::endl;
    else if(isfull())
        std::cout << "栈已满!" << std::endl;
    else
        std::cout << "栈正常!" << std::endl;
}

template <typename Type>
void Stack<Type>::DisplayStackData()
{
    for(int i = 0; i < stack_top; i++)
    {
        std::cout << "stack[" << i << "] = "
                  << items[i] << std::endl;
    }
}

#endif // MYTEST_H_INCLUDED

主程序:

#include "mytest.h"
//主程序
int main()
{
    Stack<int> stack1;
    std::cout << "/************压栈操作**********/" << std::endl;
    for(int i = 0; i < 10; i++)
    {
        stack1.push(( i + 1) * 10 );
    }
    stack1.DisplayStackState();
    std::cout << "栈中的数据为:" << '\t' <<std::endl;;
    stack1.DisplayStackData();
    std::cout << std::endl;

    std::cout << "/************弹栈操作**********/" << std::endl;
    int pop_data;
    std::cout << "弹出栈的数据为:";
    for(int i = 0; i < 5; i++)
    {
        stack1.pop(pop_data);
        std::cout << pop_data << ' ';
    }
    std::cout << std::endl;
    stack1.DisplayStackState();
    std::cout << "栈中的数据为:" << '\t' << std::endl;;
    stack1.DisplayStackData();
    std::cout << std::endl;

    std::cout << "/************继续弾栈**********/" << std::endl;
    std::cout << "弹出栈的数据为:";
    for(int i = 0; i < 5; i++)
    {
        stack1.pop(pop_data);
        std::cout << pop_data << ' ';
    }
    std::cout << std::endl;
    stack1.DisplayStackState();


    return 0;
}

执行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_40579095/article/details/81909507