栈的结构定义:
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
(1)链栈的初始化:
构造空栈,栈顶指针置为空即可
Status InitStack(LinkStack &S)
{
S=NULL;
return OK;
}
(2)入栈:
Status Push(LinkStack &S,SElemType e)
{
p=new StackNode; //生成新结点
p->data=e; //将结点的数据域赋值为e
p->next=S; //将新结点插入栈顶
S=p; //修改栈顶指针为p
return OK;
}
(3)出栈:
Status Pop(LinkStack &S,SElemType &e)
{
if(S==NULL)
return false;
e=S->data; //将栈顶赋给e
StackNode *p=S; //用p临时保存栈顶元素空间,以备释放
S=S->next; //修改栈顶指针
delete p; //释放原栈顶元素空间
return true;
}
(4)取链栈栈顶元素:
SElemType GetTop(LinkStack S)
{
if(S)
return S->data;
}
(5)遍历链栈:
void StackTraverse(LinkStack S)
{
StackNode *p=S;
while(p)
{
此处可以写对每个结点进行的操作
p=p->next;
}
}