栈的链式存储结构与单链表类似,但操作受限制,插入和删除只能在链栈的栈顶进行
栈顶指针Top就是链表的头指针,为了方便操作,使链栈带一空的表头结点,表头后的第一个结点就是链栈的栈顶结点
其他的结点通过Next指针链接,栈底结点的Next为NULL
typedef struct SNode* PtrToSNode;
typedef int ElementType;
struct SNode
{
ElementType Data;
PtrToSNode Next;
};
typedef PtrToSNode Stack;
//带头结点的链栈
Stack CreateStack()
{
//构建一个栈的头结点,返回该结点指针
Stack S;
S=(SNode *)malloc(sizeof(struct SNode));
S->Next=NULL;
return S;
}
//判断链栈是否为空,若为空,则只存在头结点,Next指针为空
bool IsEmpty(Stack S)
{
return (S->Next==NULL);
}
//压栈
bool Push(Stack S,ElementType X)
{
PtrToSNode Tmpcell;
Tmpcell=(PtrToSNode)malloc(sizeof(struct SNode));
Tmpcell->Data=X;
Tmpcell->Next=S->Next;
S->Next=Tmpcell;
return true;
}
//出栈 删除并返回栈顶元素
ElementType Pop(Stack S)
{
PtrToSNode FirstCell;
ElementType TopElem;
if(IsEmpty(S))
{
printf("the stack is empty\n");
return ERROR;
}
else
{
FirstCell=S->Next;
TopElem=FirstCell->Data;
S->Next=FirstCell->Next;
free(FirstCell);
return TopElem;
}
}