栈是一种线性的数据结构,其特点是先进后出,一般用于处理括号匹配,dfs等问题
在使用栈的时候应该特别注意栈的大小,尽量不要爆栈,若发生爆栈则要扩大栈的空间
处理overflow的函数 overFlow();
先开一个新的更大的数组,然后将原数组的值赋给这个数组,同时更新maxSize的值
同时不要忘了删除原来的数组
代码
template<class T>
void Stack<T>::overFlow()
{
maxSize += stackIncreament;//更新栈的最大size
T* newelements = new T[maxSize];//新数组
for (int i = 0; i <= top; i++)newelements[i] = elements[i];//拷贝数组
delete[]elements;//删除原数组
elements = newelements;
}
代码如下:
#include<iostream>
using namespace std;
const int maxS = 50;
const int stackIncreament = 20;
template<class T>
class Stack
{
public:
Stack(int sz = maxS);
~Stack() { delete[] elements; }
void push(const T x);
void pop();
T getTop();
bool isEmpty()const { return top == -1; }
bool isFull()const { return top == maxSize - 1; }
int getSize()const { return top + 1; }
void makeEmpty() { top = -1; }
void input();
private:
T* elements;
int top;
int maxSize;
void overFlow();
};
template<class T>
Stack<T>::Stack(int sz)
{
elements = new T[sz];
top = -1;
maxSize = sz;
}
template<class T>
void Stack<T>::push(const T x)
{
if (isFull())
{
overFlow();
}
elements[++top] = x;
}
template<class T>
void Stack<T>::pop()
{
if (isEmpty())
{
cerr << "栈为空" << endl;
return;
}
top--;
}
template<class T>
T Stack<T>::getTop()
{
if (isEmpty())
{
cerr << "栈为空" << endl;
return -1;
}
return elements[top];
}
template<class T>
void Stack<T>::overFlow()
{
maxSize += stackIncreament;
T* newelements = new T[maxSize];
for (int i = 0; i <= top; i++)newelements[i] = elements[i];
delete[]elements;
elements = newelements;
}
template<class T>
void Stack<T>::input()
{
int cnt = 0;
cout << "请输入元素个数" << endl;
cin >> cnt;
while (cnt <= 0)
{
cout << "请输入元素个数" << endl;
cin >> cnt;
}
while (cnt--)
{
T temp;
cin >> temp;
push(temp);
}
}