【栈】
顺序栈
1.实现
typedef struct SNode *Stack;
struct SNode {
ElementType Data[MaxSize];
int Top; // 栈顶指针
};
2.创建空栈
Stack CreatStack()
{
Stack PtrS;
PtrS = (Stack)malloc(sizeof(struct SNode));
PtrS -> Top = -1;
return PtrS;
}
2.入栈
void Push(Stack PtrS,ElementType item)
{
if(PtrS -> Top == MaxSize - 1)
return; // 栈满
else {
PtrS -> Data[++ (Ptr -> Top)] = item;
return;
}
}
3.出栈
ElementType Pop(Stack PtrS)
{
if(Ptr -> Top == -1)
return; // 栈空
else
return (PtrS -> Data[(PtrS -> Top) --]);
}
4.判空
int IsEmpty(Stack PtrS)
{
if(S -> Top == -1)
return 1;
else
return 0;
}
4.判满
int IsFull(Stack PtrS)
{
if(S -> Top == MaxSize - 1)
return 1;
else
return 0;
}
链栈
- 栈顶元素就是第一个元素(头空结点的下一个)
1.实现
typedef struct SNode *Stack;
struct SNode {
ElementType Data;
Stack Next;
};
2.创建空栈
// 建立一个只有头空结点的空栈
Stack CreateStack()
{
Stack S;
S = (Stack)malloc(sizeof(struct SNode));
S -> Next = NULL;
return S;
}
3.入栈
void Push(ElementType item,Stack S)
{
struct SNode *tmpNode;
tmpNode = (struct Node *)malloc(sizeof(struct SNode));
tmpNode -> Element = item;
tmpNode -> Next = S -> Next;
S -> Next = tmpNode;
}
4.出栈
ElementType Pop(Stack S)
{
struct SNode *FirstNode;
ElementType FirstEle;
if(IsEmypty(S))
return;
else {
FirstNode = S -> Next;
S -> Next = FirstNode -> Next;
FirstEle = FirstNode -> Data;
free(FirstNode);
return FirstEle;
}
}
5.判空
int IsEmpty(Stack S)
{
return (S -> Next == NULL);
}