#include <assert.h>
#include <iostream>
#include "stack.h"
using namespace std;
const int stackIncreament = 20;//栈溢出时扩展空间的增量
template<class T>
class SeqStack: public Stack<T> //顺序表的类定义
{
public:
SeqStack(int sz = 50); //建立一个空栈
~SeqStack() //析构函数
{
delete [] elements;
}
void Push(const T& x);
//如果IsFull(),则溢出处理,否则把x插入到栈的栈顶。
bool Pop(T& x);
//如果IsEmpty(),则不执行退栈,返回false;否则退掉栈顶的元素,返回true,
//退出的元素值通过引用型参数x返回。
bool getTop(T& x) const;
//如果IsEmpty(),返回false;否则返回true,通过引用型参数x得到栈顶元素的值。
bool IsEmpty() const
{
return (top == -1) ? true:false;
}
//如果栈中元素个数等于0,则返回true,否则返回false
bool IsFull() const
{
return (top == -1) ? true : false;
}
//如果栈中元素个数等于maxSize,则返回true,否则返回false。
int getSize() const //函数返回栈中元素个数
{
return top+1;
}
void MakeEmpty() //清空栈的内容
{
top = -1;
}
friend ostream& operator<<(ostream& os,SeqStack<T>& s);
//输出占中元素的重载操作<<
private:
T *elements;
int top;
int maxSize;
void overflowProcess();
void stackFull();
};
template<class T>
SeqStack<T>::SeqStack(int sz)//;top(-1),maxSize(sz)
{
//建立一个最大尺寸为sz的空栈,若分配不成功则错误处理
top = -1;
maxSize = sz;
elements = new T[maxSize];
assert(elements != NULL);
}
template<class T>
void SeqStack<T>::overflowProcess()
{
T * newArray = new T[maxSize + stackIncreament];
if(newArray = NULL)
{
cerr << "存储分配失败!" << endl;
exit(1);
}
for(int i = 0;i <= top; i++)
newArray[i] = elements[i];
maxSize = maxSize + stackIncreament;
delete [] elements;
elements = newArray;
}
template<class T>
void SeqStack<T>::Push(const T &x)
{
if(IsFull() == true)
stackFull();
// overflowProcess();
elements[++top] = x;
}
template<class T>
bool SeqStack<T>::Pop(T& x)
{
if(IsEmpty() == true)
return false;
x = elements[top--];
return true;
}
template<class T>
bool SeqStack<T>::getTop(T& x) const
{
if(IsEmpty() == true)
return false;
x = elements[top];
return true;
}
template<class T>
ostream& operator<<(ostream& os,SeqStack<T>& s)
{
os << "top = " << s.top << endl;
for( int i = 0; i <= s.top; i++)
os << i << ":" << s.elements[i] << endl;
return os;
}
template<class T>
void SeqStack<T>::stackFull()
{
T * newArray = new T[3 * maxSize];
if(newArray = NULL)
{
cerr << "存储分配失败!" << endl;
exit(1);
}
for(int i = 0;i <= top; i++)
newArray[i] = elements[i];
maxSize = 3 * maxSize;
delete [] elements;
elements = newArray;
}