用模板类函数实现顺序栈的功能

#include <iostream>
#define MAXSIZE 10
using namespace std;

template <typename T>
class Stack
{
private:

    T value;//栈值
    T* base;
    T top;//栈顶
    int maxsize;//顺序栈的最大容量、

public:

    Stack();
    ~Stack();

    //判断栈是否为空
    bool empty();
    //判断栈是否为满
    bool full();
    //弹栈
    bool pop();
    //压栈
    bool push(int value);
    //遍历
    void show();
    //计算栈的长度
    int stacklenth();

};


//构造函数
template <typename T>
Stack<T>::Stack()
{

    base =new T[MAXSIZE];
    top = 0;
}
//析构函数
template <typename T>
Stack<T>::~Stack<T>()
{
    delete[]base;
    base = nullptr;
    cout<<"析构函数"<<endl;
}
//判断栈是否为满的实现
template<typename T>
bool Stack<T>::full(){
    return top == MAXSIZE;
}

//判断栈是否为空的实现
template<typename T>
bool Stack<T>::empty() {
    return top == 0;
}
//弹栈
template <typename T>
bool Stack<T>::pop()
{
    if(empty())
    {
        return false;
    }
    top--;
    return true;
}
//压栈
template<typename T>
bool Stack<T>::push(int value) {
    if (full()) {
        cout << "栈已经满了,无法继续添加元素" << endl;
        return false;
    }
    base[top] = value;
    top++;
    cout << "值压入成功!" << endl;
    return true;
}
//遍历
template <typename T>
void Stack<T>::show()
{
    for(int i = top-1;i>=0;i--)
    {
        cout<<base[i]<<endl;
    }
}
//计算栈的长度
template <typename T>
int Stack<T>::stacklenth()
{
    return top;
}




int main()
{
    Stack <int> s;
   s.push(7);
   s.push(5);
   s.push(5);
   s.push(57);
   s.push(81);
   s.show();
   s.pop();
   s.pop();
   s.show();




    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值