栈的链式存储结构称之为链栈,链栈是没有头结点的单链表,其中头指针为栈顶指针
一 链栈类型定义
二 链栈的数据类型
typedef struct stacknode
{
DataType data;
struct stacknode *next;
}StackNode;
typedef struct
{
StackNode *top;//栈顶指针
}LinkStack;
注:这里的LinkStack是为了方面在函数中修改top本身
三 链栈的基本操作
// 置栈空
void InitStack(LinkStack *S)
{
S->top=NULL;
}
// 判栈空
int StackEmpty(LinkStack *S)
{
return S->top==NULL;
}
//进栈
void Push(LinkStack *s,DataType x)
{
StackNode *p = (StackNode *)malloc(sizeof(StackNode));
p->data = x;
p->next = S->top;//将新节点*p插入到链栈头部
S->top = p;
}
//退栈
DataType Pop(LinkStack *S)
{
DataType x;
StackNode *p = S->top;//保存栈顶指针
if(StackEmpty(S))
Error("Stack underflow");//下溢
x = p->data;//保存栈顶数据
S->top = p->next;//将栈顶节点从链上摘下来
free(p);
return x;
}