栈的顺序存储结构

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;
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值