#include<iostream>
#include<exception>
using namespace std;
#define NUM 5
//用数组结构实现大小固定的队列和栈
class ArrayIndexOutOfBoundsException:public exception
{
private:
const char*ptr;
public:
ArrayIndexOutOfBoundsException(const char*ptr)
{
this->ptr = ptr;
}
virtual char const *what()
{
cout<<this->ptr<<endl;
return ptr;
}
};
class MyStack
{
private:
int *array;
int idx;
int N;
public:
MyStack(int N);
~MyStack();
void push(int element);
int pop();
int peek();
void printStack();
};
MyStack::MyStack(int N)
{
this->N = N;
array = new int[N];
idx=0;
}
MyStack::~MyStack()
{
delete[] this->array;
}
void MyStack::push(int element)
{
if(idx == N)
throw ArrayIndexOutOfBoundsException("栈已满");
else
array[idx++] = element;
}
int MyStack::pop()
{
if(idx == 0)
throw ArrayIndexOutOfBoundsException("栈中无元素");
else
return array[--idx];
}
int MyS
C++用数组实现一个固定大小的栈/队列
最新推荐文章于 2024-07-04 16:05:07 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)