#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 <iostream>
#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();
}
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。