栈(数据结构):一种后进先出的数据结构
按照实现方式的不同可以分为顺序栈和链栈两种。
顺序栈:用顺序表实现,分配一个连续的存储空间用于存放栈中的元素
//置栈空
void InitStack(Stack &st)
{
st.top = -1;
}
//进栈,将元素x进到栈st中
void Push(Stack &st, ElemType x)
{
if (st.top == MaxSize-1) //栈溢出
return;
st.s[++st.top] = x;
}
//出栈,将栈顶元素弹出保存到x中
void Pop(Stack &st, ElemType &x)
{
if (st.top == -1) //栈为空
return;
x = st.s[st.top--];
}
//取得栈顶元素,返回到x中
void GetTop(Stack st, ElemType &x)
{
if (st.top == -1) //栈为空
return;
x = st.s[st.top];
}
//判断栈空
bool IsStackEmpty(Stack st)
{
if (st.top == -1)
return true;
else
return false;
}
链栈:栈的链式存储,本质上可以看做是只允许在表头进行插入和删除运算的单链表
//置栈空
void InitStack(SNode *&st)
{
st = NULL;
}
//进栈,将元素x进到栈st中
void Push(SNode *&st, ElemType x)
{
SNode *p;
p = new SNode;
p->data = x;
p->next = NULL;
if (st == NULL)
st = p;
else{
p->next = st;
st = p;
}
}
//出栈,将栈顶元素弹出保存到x中
void Pop(SNode *&st, ElemType &x)
{
if (st == NULL)
return;
SNode *p = st;
x = st->data;
st = st->next;
delete p;
}
//取得栈顶元素,返回到x中
void GetTop(SNode *st, ElemType &x)
{
if (st == NULL)
return;
x = st->data;
}
//判断栈空
bool IsStackEmpty(SNode *st)
{
if (st == NULL)
return true;
else
return false;
}