头文件
const int MAX_STACK_NUM = 4;
class Stack
{
public:
Stack();
~Stack();
int pop();
void push(int x);
int peek() const;
int count();
private:
int m_pos;//m_pos-1为栈顶元素的位置
int m_data[MAX_STACK_NUM];
};
cpp文件
#include "stack.h"
int Stack::peek()const
{
if(m_pos<=0)
{
throw "stack is empty";
return -1;
}
else
{
return m_data[m_pos-1];
}
}
int Stack::pop()
{
if(m_pos<=0)
{
throw "stack is empty";
return -1;
}
else
{
m_pos--;
return m_data[m_pos];
}
}
void Stack::push(int x)
{
if(m_pos>=MAX_STACK_NUM)
{
throw "stack is full";
}
else
{
m_data[m_pos] = x;
m_pos++;
}
}
Stack::Stack():m_pos(0)
{
}
Stack::~Stack()
{
}
int Stack::count()
{
return m_pos;
}