栈也是一种简单常用的数据结构,他的特点是先进先出。
现代化计算机将栈操作作为指令系统的一部分,栈也就有可能成为计算机科学中在数组之后最基本的数据结构。所以,栈的重要性就不用多说了。
其实现思路也比较简单,这里就不多解释了,直接看代码吧
#include "Stack.h"
#include <stdlib.h>
struct Node
{
ElementType Element;
PtrToNode Next;
};
void FatalError(char * s)
{
}
void Error(char * s)
{
}
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 CreateStack 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->Element = X;
TmpCell->Next = S->Next;
S->Next = TmpCell;
}
}
ElementType Top(Stack S)
{
if(!IsEmpty(S))
return S->Next->Element;
Error("Empty stack");
return 0;
}
void Pop(Stack S)
{
PtrToNode FirstCell;
if(IsEmpty( S ))
Error("Empty stack");
else
{
FirstCell = S->Next;
S->Next = S->Next->Next;
free(FirstCell);
}
}
void DisposeStack(Stack S)
{
while(!IsEmpty(S))
Pop(S);
}
int main()
{
Stack S = CreatStack();
Push(1,S);
Push(2,S);
Push(3,S);
//DisposeStack(S);
while(!IsEmpty(S))
{
printf("%d\n",Top(S));
Pop(S);
}
}
按照惯例,同样在后面加了个main函数用于测试,顺便把书上没有的几个实现也补上了
注:代码改编自《数据结构与算法分析》第二版