stackArray.h
#include
class StackArray
{
public:
StackArray(int MaxStackSize=10);
~StackArray() {if(stack) delete stack;};
bool IsEmpty() const{return top==-1;} //栈空返回1,否则返回0
bool IsFull() const{return top==MaxSize-1;} //栈满返回1,否则返回0
int & GetTop() const; //获得栈顶元素
bool Push(const int& x); //元素x入栈
bool Pop(int& x); //元素出栈,并保存在x中
bool Pop(); //元素出栈
void ClearStack() {top = -1;}; //清除栈中所有元素
void Output(); //输出栈元素
private:
int top; //栈顶
int MaxSize; //最大栈顶值
int *stack; //堆栈元素数组,可以使用其他数据类型
};
stackArray.cpp
#include
#include "stackArray.h"
#include "error.h"
StackArray::StackArray(int MaxStackSize)
{//构造函数
MaxSize = MaxStackSize;
stack = new int[MaxSize];
if(stack == NULL)
throw NoMem();
top = -1;
}
//返回栈顶元素
int &StackArray::GetTop() const
{
if(IsEmpty())
throw OutOfBounds();
else
return stack[top];
}
//添加元素x
bool StackArray::Push(const int& x)
{
if(IsFull())
throw OutOfBounds();
stack[++top] = x;
return true;
}
//删除栈顶元素,并送入x中
bool StackArray::Pop(int &x)
{
if(IsEmpty())
throw OutOfBounds();
x=stack[top--];
return true;
}
//删除栈顶元素
bool StackArray::Pop()
{
if(IsEmpty())
throw OutOfBounds();
top--;
return true;
}
//输出显示栈中的元素
void StackArray::Output()
{
for(int i=0; i<=top; i++)
cout<
<<
" ";
cout<
}
异常处理头文件error.h
#include
using namespace std;
//内存不足异常
class NoMem
{
public:
NoMem() { cout<<"Memory is not enough"; };
};
//越界异常
class OutOfBounds
{
public:
OutOfBounds() { cout<<"out of bounds"; };
};
测试文件:stack.app
#include
#include "stackArray.h"
using namespace std;
int main()
{
StackArray *stackArray = new StackArray(10);
stackArray->Push(5);
stackArray->Push(6);
stackArray->Push(62);
stackArray->Push(12);
cout<<"当前栈中元素为:"<
stackArray->Output();
int x;
stackArray->Pop(x);
cout<<"出栈元素:"<
<
x = stackArray->GetTop();
cout<<"栈顶元素:"<
<
cout<<"当前栈中元素为:"<
stackArray->Output();
return 0;
}
运行结果: