数据结构 - c++模板类实现栈Stack

#ifndef STACK_HPP
#define STACK_HPP

#include <cassert>

template <class T> 
class Stack
{
private:
    //the increment when the space are not enough 
    const int INCREMENT = 32;
    //total size of current stack  
    int totalSize;
    //size of pushed elements , also the index of top element plus one
    int size;
    //the pointer to the bottom 
    T * element;

    //when the space is not enough,the function was called
    bool IncreaseSpace();
public:
    Stack();
    ~Stack();
    
    //check if the stack is empty,ruturn true when it's empty
    bool IsEmpty();
    
    //push the element to the stack
    void Push(T e);
    
    //pop the top element,return NULL when the stack is empty
    T Pop();
    
    //get the top element without popping out of the stack, return NULL when the stack is empty
    T Top();

    //get size of the stack
    int Size();

};


template<class T>
bool Stack<T>::IncreaseSpace()
{
    T * t = NULL;
    t = new T[totalSize + INCREMENT];
    if(t == NULL)
        return false;
    else
    {
        for (int i = 0; i < size; ++i)
            t[i] = element[i];
        delete[] element;
        element = t;
        return true;
    }
}

template<class T>
Stack<T>::Stack():totalSize(INCREMENT),size(0)
{
    element = new T[INCREMENT];
}

template<class T>
Stack<T>::~Stack()
{
    delete[] element;
}

template<class T>
bool Stack<T>::IsEmpty()
{
    return (size == 0);
}

template<class T>
void Stack<T>::Push(T e)
{
    ++size;
    if(size > totalSize)
        assert(IncreaseSpace());
    element[size - 1] = e;
}

template<class T>
 T Stack<T>::Pop()
 {
     assert(size != 0);
     --size;
     return element[size];
 }

template<class T>
T Stack<T>::Top()
{
    assert(size != 0);
    return element[size - 1];
}

template<class T>
int Stack<T>::Size()
{
    return size;
}

#endif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值