学习笔记…
#include<stdio.h>
#include<stdlib.h>
#define Error( Str ) fprintf( stderr, "%s\n", Str ), exit( 1 )//可大量简化后面代码量
#define EmptyTOS -1
#define MinStackSize 5
typedef int ElementType;
typedef struct StackRecord{
int TopOfStack; //栈顶
int Capacity; //容量域
ElementType *array; //存储元素的数组
}*Stack;
//判断是否为空
int IsEmpty(Stack S)
{
return S->TopOfStack == EmptyTOS;
}
//判断是否满栈
int IsFull(Stack S)
{
return S->TopOfStack == S->Capacity - 1;
}
//清空栈
void MakeEmpty(Stack S)
{
S->TopOfStack = EmptyTOS;//直接使TopOfStack为-1
}
//创建栈
Stack CreateStack(int MaxElement)
{
Stack S;
if(MaxElement < MinStackSize){
Error("Stack Size is too small!");
}
S = malloc(sizeof(struct StackRecord));
if(S == NULL)
Error("Out of space!!!");
S->array = malloc(sizeof(ElementType) * MaxElement);//开辟一个空间为sizeof(ElementType) * MaxElement位的空间
if(S->array == NULL)
Error("Out of space!");
S->Capacity = MaxElement;
MakeEmpty(S);
return S;
}
void Push(ElementType X, Stack S)
{
if(IsFull(S))
Error("Full Stack");
S->array[++S->TopOfStack] = X;//++S->TopOfSrack是 S->TopOfSrack立马增一
}
void Pop(Stack S)
{
if(IsEmpty(S))
Error("Empty Stack");
S->TopOfStack--;
}
ElementType TopAndPop(Stack S)
{
if(!IsEmpty(S))
return S->array[S->TopOfStack--];
else
{
Error("Empty Stack");
return 0;
}
}
//销毁栈
void DisposeStack(Stack S)
{
if(S != NULL)
{
free(S->array);
free(S);
}
}
//返回栈顶元素
ElementType Top(Stack S)
{
if(!IsEmpty(S))
return S->array[S->TopOfStack];
else
{
Error("Empty Stack");
return 0;
}
}
//遍历并打印栈
void TravalStack(Stack S)
{
if(!IsEmpty(S)){
for(; S->TopOfStack != EmptyTOS; S->TopOfStack--){
printf("%d\n",Top(S));
}
}
else
Error("Empty Stack");
}
int main(){
Stack S;
S = CreateStack(10);
Push(7,S);
Push(6,S);
Push(5,S);
Push(4,S);
Push(3,S);
printf("%d\n",Top(S));
Pop(S);
Pop(S);
TravalStack(S);
DisposeStack(S);
return 0;
}
用数组实现栈花费时间为很小的常数 应该尽可能写出各种错误检测,如果错误检测的代码量确实很大,可以省略