棧的鏈式存儲結構實際上就是一個單鏈表,叫做鏈棧。插入和刪除操作只能在鏈棧的棧頂進行。
/* 定義鏈棧 */
typedef struct SNode * Stack;
struct SNode{
ElementType Data;
struct SNode *Next;
};
/* 堆棧初始化、建立空棧 */
Stack CreateStack()
{
/* 建立一個堆棧的頭節點,返回指針 */
Stack S;
S = (Stack)malloc(sizeof(struct SNode));
S->Next=NULL;
return S;
}
/* 判斷棧是否為空 */
int IsEmpty(Stack S)
{
/* 空返回1,否則返回0 */
return(S->Next == NULL);
}
/* Push 入棧 元素item壓入堆棧S */
void Push(ElementType item,Stack S)
{
struct SNode * TmpCell;
TmpCell=(struct SNode * )malloc(sizeof(struct SNode));
TmpCell->Element =item;
TmpCell->Next=S->Next;
S->next=TmpCell;
}
/*Pop 出棧 刪除并返回堆棧S的棧頂元素*/
ElementType Pop(Stack S)
{
struct SNode * FirstCell; //指向棧頂元素
ElementType TopElem; //棧頂元素
if(IsEmpty(S)){
printf("the Stack empty"); return NULL;
}else{
FirstCell = S->Next;
S->Next = FirstCell->Next;
TopElem=FirstCell->Element;
free(FirstCell);
return TopElem;
}
}