链栈的初始化
Status InitStack(Stack* &s)
{
s = (Stack*)malloc(sizeof(Stack));
s->next = NULL;
return OK;
}
元素入栈
- 为入栈元素e分配空间,用指针p指向
- 将新节点数据域置为e
- 将新节点插入栈顶
- 修改栈顶指针为p
Status Push(Stack *s,ElemType e)
{
Stack *p = (Stack*)malloc(sizeof(Stack));
//头插法插入节点
p->data = e;
p->next = s->next;
s->next = p;
return OK;
}
元素出栈
- 判断栈是否为空,若空则返回ERROR
- 将栈顶元素赋给e
- 临时保存栈顶元素的空间,以备释放
- 修改栈顶指针,指向新的栈顶元素
- 释放原栈顶元素的空间