堆栈C++链表实现方法(堆栈–链表)
需注意链表表头作为链表顶端
1.链表结构
typedef struct SNode *Stack;
struct SNode
{
ElementType Data;
struct SNode *Next;
};
2.堆栈初始化(生成空栈)
Stack CreateStack()
{
Stack S;
S=(Stack)malloc(sizeof(SNode));
S->Next = NULL;
return S;
}
3.判断堆栈S是否为空
int IsEmpty(Stack S)
{
return(S->Next == NULL)
}
4.push操作
void Push(ELementType item, Stack S)
{
struct Stack *TmpCell;
TmpCell =(Stack)malloc(sizeof(SNode));
TmpCell->Element=item;
TmpCell->Next=S->Next;
S->Next=TmpCell;
}
5.pop操作
ElementType Pop(Stack S)
{
Stack *fistcell;
if(isEmpty(S))
{
printf("堆栈空");
return NULL;
}
else
{
firstcell = S->Next;
S->Next = firstcell -> Next;
TopELem = firstcell -> Element;
free(firstcell);
return TopElem;
}
}