栈ADT
1栈模型
栈是限制插入和删除只能在一个位置上进行的表,该位置是表的末端,叫做栈顶(top),对栈的基本操作有push(进栈)和pop(出栈),前者相当于插入,后者则是删除最后插入的元素。
栈是后进先出的(LIFO)表,一般的模型中,存在某个元素位于栈顶,而该元素是唯一的可见元素。只有栈顶元素是可以访问的
2 栈的实现
栈是一个表,因此任何实现表的方法都能实现栈。两种方法实现:一种是指针,一种是使用数组
2.1 栈的数组实现
栈的数组实现是目前用的最多的方法
栈的声明:
#ifndif _Stack_h
struct StackRecord;
typedef struct StackRecord *Stack;
int IsEmpty(Stack S);
int IsFull(Stack S);
Stack CreateStack(int MaxElements);
void DisposeStack(Stack S);
void MakeEmpty(Stack S);
void Push(ElementType X,Stack S);
ElementType Top(Stack S);
void Pop(Stack S);
ElementType TopAndPop(Stack S);
#endif
#define EmptyTOS(-1)
#define MinStackSize(5)
struct StackRecord
{
int Capacity;
int TopOfStack;
ElementType *Array;
};
栈的创建:
Stack CreatStack(int MaxElements)
{
Stack S;
if(MaxElements<MinStackSize)
Error("Stack size is too small");
S=malloc(sizeof(struct StackRecord));
if(S==NULL)
FatalError("out of space");
S->Array=malloc(sizeof(ElementType)*MaxElements)
if(S->Array=NULL)
FatalError("out of space");
S->Capacity=MaxElements;
MakeEmpty(S);
return S;
}
释放栈:
void DisposeStack(Stack S)
{
if(S!=NULL)
{
free(S);
free(S->Array);
}
}
检测一个栈是否空栈:
int IsEmpty(Stack S)
{
return S->TopOfStack == EmptyTOS;
}
创建一个空栈:
void MakeEmpty(Stack S)
{
S->TopOfStack=EmptyTOS;
}
进栈:
void Push(ElementType X,Stack S)
{
if(IsFull(S))
Error("Full stack");
else
S->Array[++S->TopOfStack]=X;
}
出栈:
void Pop(Stack S)
{
if(IsEmpty(S))
Error("Empty stack");
else
S->TopOfStack--;
}
给出栈顶元素并出栈:
ElementType TopAndPop(Stack S)
{
if(!IsEmpty(S))
return S->Array[S->TopOfStack--];
else
{
Error("empty stack");
return 0;
}
}