#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
数据结构 - c++模板类实现栈Stack
最新推荐文章于 2021-03-04 20:36:48 发布