Files
Data_Structure/OrigFiles/树和二叉树/5-1-BiTree/SqStack_bt.h

76 lines
1.4 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//栈
template <class DT>
struct SqStack // 顺序栈
{
BTNode<DT>* *base; // 栈首址
int top; // 栈顶指针
int stacksize; // 栈容量
};
//【算法3.1】 初始化栈
template <class DT>
void InitStack(SqStack<DT> &S, int m)
{
S.base=new BTNode<DT>* [m]; // 申请栈空间
if(S.base==NULL)
{
cout<<"未创建成功!";
exit (1);
}
S.top=-1; // 空栈
S.stacksize=m; // 栈容量为m
}
//算法3.2】 销毁栈
template <class DT>
void DestroyStack(SqStack<DT> &S)//析构函数
{
delete [] S.base; //释放栈空间
S.top=-1;
S.stacksize=0;
}
//【算法3.3】
template<class DT>
bool Push(SqStack<DT> &S,BTNode<DT>* e)
{
if(S.top==S.stacksize-1) // 栈满,不能插入
return false;
S.top++;
S.base[S.top]=e;
return true; // 插入成功返回true
}
//【算法3.4】 出栈
template<class DT>
bool Pop(SqStack<DT> &S,BTNode<DT>* &e)
{
if(S.top==-1) //栈空
return false;
e=S.base[S.top];
S.top--;
return true; // 出栈成功返回true
}
template<class DT> // 获取栈元素
bool GetTop(SqStack<DT> &S,BTNode<DT>* &e)
{
if(S.top==-1) // 栈空返回false
return false;
e=S.base[S.top]; // 取栈元素
return true; // 返回true
}
// 测栈空
template<class DT>
bool StackEmpty(SqStack<DT> S)
{
if(S.top==-1) // 栈空返回true
return true;
else // 栈非空返回false
return false;
}