最近开始学习数据结构,说是学习,以前在大学里面没有好好学习,纯粹是为了考试而学的,现在自己写了个stack的c++实现,贴出来
template<class ElemType>
class cStack
{
public:
~cStack();
bool InitStack();
ElemType GetTop();
bool Empty();
bool Push(ElemType e);
bool Pop(ElemType &e);
int Size();
private:
ElemType * m_pbase;
int m_top;
int m_stacksize;
};
//.cpp文件
#include "stdafx.h"
#include "bindtest.h"
#include <iostream>
using namespace std;
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 10
template<class ElemType>
bool cStack<ElemType>::InitStack()
{
m_pbase = new ElemType[STACK_INIT_SIZE];
if (!m_pbase)
{
return false;
}
m_top = 0;
m_stacksize = STACK_INIT_SIZE;
return true;
}
template<class ElemType>
cStack<ElemType>::~cStack()
{
delete []m_pbase;
}
template<class ElemType>
bool cStack<ElemType>::Empty()
{
return m_top == 0;
}
template<class ElemType>
ElemType cStack<ElemType>::GetTop()
{
if (m_top != 0)
{
return m_pbase[m_top - 1];
}
}
template<class ElemType>
bool cStack<ElemType>::Push(ElemType e)
{
if (m_top == STACK_INIT_SIZE)
{
ElemType* pOld = m_pbase;
m_pbase = new ElemType[m_stacksize + STACKINCREMENT];
if (!m_pbase)
{
return false;
}
memcpy((void*)m_pbase,(void*)pOld,m_stacksize);
delete pOld;
}
m_stacksize += STACKINCREMENT;
m_pbase[m_top++] = e;
return true;
}
template<class ElemType>
bool cStack<ElemType>::Pop(ElemType &e)
{
if (m_top == 0)
{
return false;
}
e = m_pbase[--m_top];
}
template<class ElemType>
int cStack<ElemType>::Size()
{
return m_top ;
}