基于线性表的堆栈
#ifndef IOSTREAM
#include <iostream>
#endif
template<class T>
class Stack
{
public:
Stack(int MaxSize=10);
~Stack();
bool IsEmpty()const{return top==0;}
bool IsFull()const{return top==MaxTop;}
T Top()const;
Stack<T>&Add(const T &x);
Stack<T>&Delete(T&x);
int GetStackSize()const;//确定堆栈的大小
private:
int top;
int MaxTop;
T *stack;//堆栈元素数组
};
//构造函数
template<class T>
Stack<T>::Stack(int MaxSize)
{
MaxTop=MaxSize-1;
stack=new T [MaxSize];
top=-1;//因为top=0的时候等于已经有一个元素了,所以这里为-1
}
//析构函数
template<class T>
Stack<T>::~Stack()
{
delete [] stack;
}
//弹出栈顶
template<class T>
T Stack<T>::Top()const
{
if(IsEmpty()) throw OutOfBounds();
else
return stack[top];
}
//压入栈
template<class T>
Stack<T>&Stack<T>::Add(const T &x)
{
if(IsFull())
throw NoMem();
top++;
stack[top]=x;
return *this;
}
//弹出栈
template<class T>
Stack<T>&Stack<T>::Delete(T&x)
{
if((IsEmpty()))
throw OutOfBounds();
x=stack[top];
top--;
return *this;
}
//确定堆栈的大小
template<class T>
int Stack<T>::GetStackSize()const
{
if(IsEmpty())
throw OutOfBounds();
int len=top;
return ++len;
}
本文章转载请务必注明出处或保存此段。c++/lua/windows逆向交流群:69148232

浙公网安备 33010602011771号