C++实现栈数据结构-创新互联
#ifndef __STACK__
#define __STACK__
class CStack
{
int * m_pData;
int m_nCount;
int m_nPos;
public:
CStack(int nLength);
~CStack();
bool isFull();
bool isEmpty();
void push(const int & value);
bool pop(int &value);
};
CStack::CStack(int nLength)
{//创建栈类时,确定其大小
m_pData = new int[nLength];
memset(m_pData,0,nLength);
m_nPos = -1;
m_nCount = nLength;//用来判断栈是否满
}
bool CStack::isFull()
{
return m_nPos == m_nCount-1;
}
bool CStack::isEmpty()
{
return m_nPos == -1;
}
void CStack::push(const int & value)
{
if(!isFull())
{
m_pData[++m_nPos] = value;
}
}
bool CStack::pop(int &value)
{
if(isEmpty())return false;
value = m_pData[m_nPos--];
return true;
}
CStack::~CStack()
{
delete m_pData;
}
#endif调用方法如下:

#include#include "stack.h" int main(int argc, char* argv[]) { CStack stack = 5; stack.push(1); stack.push(2); stack.push(3); stack.push(4); stack.push(5); stack.push(6); int c =0; stack.pop(c); cout << c << endl; stack.pop(c); cout << c << endl; stack.pop(c); cout << c << endl; stack.pop(c); cout << c << endl; stack.pop(c); cout << c << endl; stack.pop(c); cout << c << endl; getchar(); }
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
分享标题:C++实现栈数据结构-创新互联
路径分享:http://www.jxjierui.cn/article/ipddo.html


咨询
建站咨询
