堆栈的c++实现

最近开始学习数据结构,说是学习,以前在大学里面没有好好学习,纯粹是为了考试而学的,现在自己写了个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 ;
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值