堆栈(简称栈) 是一种操作受限的线性表,只允许在表的同一端进行插入和删除操作,且这些操作是按先进后出的原则进行的。
template <class T>
struct SLNode
{
T data; //数据域
SLNode<T> *next; //指针域
SLNode(SLNode *nextNode = NULL) //构造函数
{
next = nextNode;
}
SLNode(const T &item, SLNode *nextNode = NULL) //构造函数
{
data = item;
next = nextNode;
}
};
//顺序栈
template <class T>
class AStack
{
public:
AStack(int MaxStackSize) //构造函数
{
size = MaxStackSize;
stackArray = new T[MaxStackSize];
top = -1;
}
~AStack() //析构函数
{
delete []stackArray;
}
bool Push(const T &item) //向栈顶压入一个元素
{
if (IsFull())
{
cout << "Pushing into a full stack!" << endl;
return false;
}
stackArray[++top] = item;
return true;
}
bool Pop(T &item) //从栈顶弹出一个元素
{
if (IsEmpty())
{
cout << "Poping from an empty stack!" << endl;
return false;
}
item = stackArray[top--];
return true;
}
bool Peek(T &item) const //存取栈顶元素
{
if (IsEmpty())
{
cout << "Peeking from an empty stack!" << endl;
return false;
}
item = stackArray[top];
return true;
}
int IsEmpty() const //检测栈是否为空
{
return top == -1;
}
int IsFull() const //检测是否满栈
{
return top == size-1;
}
void clear() //清空栈
{
top = -1;
}
private:
int size; //数组的规模
T *stackArray; //存放堆栈元素的数组
int top; //栈顶所在数组元素的下标
};
//链式栈类LStack的定义和实现
template <class T>
class LStack
{
public:
LStack() //构造函数
{
top = NULL;
}
~LStack() //析构函数
{
clear();
}
void clear() //清空栈
{
SLNode<T> *temp;
while(!IsEmpty())
{
temp = top->next;
delete top;
top = temp;
}
}
bool Push(const T &item) //向栈顶压入一个元素
{
top = new SLNode<T>(item, top);
return true;
}
bool Pop(T &item) //从栈顶弹出一个元素
{
if(IsEmpty())
{
cout << "Poping from an empty stack!" << endl;
return false;
}
item = top->data;
SLNode<T> *temp = top;
top = top->next;
}
bool Peek(T &item) const //读取栈顶元素
{
if(IsEmpty())
{
cout << "Poping from an empty stack!" << endl;
return false;
}
item = top->data;
return true;
}
int IsEmpty() const
{
return top == NULL;
}
private:
SLNode<T> *top;
};