堆栈的实现包括有使用指针的实现方式和使用数组的实现方式。
下面为指针的实现方式:
//堆栈也叫做LIFO结构
/* 堆栈的基本操作包括清空栈和判断是否是空栈都是栈的操作的一部分
*栈顶是唯一可见的操作
*栈的本质其实也是一个表,任何表的方法都可以用来实现栈
*栈的实现包括两种流行的方法,一种是使用指针来实现,另一种是使用数组来实现
*/
//栈的链表实现
//1.使用单链表来实现
//首先是定义:
#ifdef _Stack_h
struct Node
typedef struct Node *PtrToNode;
typedef ProToNode Stack;
int
IsEmpty(Stack S);
Stack
CreatStack(void);
void
DisposeStack(Stack S);
void
MakeEmpty(Stack S);
void
Push(ElementType X, Stack S);
ElementType
Top(Stack S)
void
Pop(Stack S);
#endif
struct Node
{
ElementType Element;
PtrToNode Next;
};
//测试堆栈是否为空
int
IsEmpty(Stack S)
{
return S->Next == NULL
}
Stack
CreatStack(void)
{
Stack S;
S = malloc(sizeof(struct Node));
if(S == NULL)
FatalError("Out of space");
S->Next == NULL;
MakeEmpty(S)
return S;
}
void //创建一个空的栈
MakeEmpty(Stack S)
{
if(S == NULL)
Error("must use CreastStack first");
else
while(!IsEmpty(S))
pop(S);
}
void //实现压栈的操作
Push(ElementType X,Stack S)
{
PtrToNode TmpCell;
TmpCell = malloc(sizeof(struct Node));
if(TmpCell == NULL)
FatalError("Out of space");
else
{
TmpCell -> ElementType = X;
TmpCell -> Next = S->Next;
S->Next = TmpCell;
}
}
ElementType
Top(Stack S)
{
if(!IsEmpty(S))
return S->next->Element;
Error("Empty Stack");
return 0; //return value is used to avoid waring
}
void
pop(Stack S)
{
PtrToNode FirstCell;
if(IsEmpty(S))
Error("Empty Stack");
else
{
FirstCell = S->next;
S->Next = S->Next->Next;
free(FirstCell);
}
}
下面是使用数组的实现方式:
#ifdef _Stack_h
struct Stackrecord;
struct StackRecord *Stack;
int IsEmpty(Stack S);
int IsFull(Stack S);
Stack CreatStack(int MaxElement);
void DisposeStack(Stack S);
void MakeEmpty(Stack S);
ElementType Top(Stack S);
void Pop(Stack S);
ElementType TopAndPop(Stack S);
#endif /*Stack.h*/
Stack CreatStack(int MaxElement)
{
Stack S;
if(MaxElement<MinStackSize)
Error("Stack is too small");
S = malloc(sizeof(struct StackRecord));
if(S ==NULL)
FatalError("Out of space");
S->Array = malloc(sizeof(ElementType)*MaxElement);
if(S->Array == NULL)
FatualError("Out of space");
S->Capacity = MaxElement;
MakeEmpty(5);
return s;
}