栈的顺序储存及基本操作

#include<stdio.h>
#include<stdlib.h>
#define EmptyTOS (-1)
#define MinStackSize ( 5 )


typedef int ElementType ;
struct StackRecord
{
int Capacity;
int TopOfStack;

ElementType *Array;
};
typedef struct StackRecord *Stack;


int IsEmpty(Stack S); //判空函数
int IsFull(Stack S); //排满函数
Stack CreatStack(int MaxElement); //创建大小为MaxElement的栈
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); //出栈并返回栈顶元素


int main(void)
{
Stack S;

S = CreatStack(10);
Push(45,S);
Push(78,S);
Push(99,S);

Pop(S);
Pop(S);


printf("%d",Top(S));


return 0;
}


Stack CreatStack(int MaxElement) //创建大小为MaxElement的栈
{
Stack S;
if(MaxElement < MinStackSize )
printf("Stack is too small\n");

S = (Stack)malloc(sizeof(struct StackRecord));
if(!S)
printf("out of space\n");

S->Array = (ElementType*)malloc(sizeof(ElementType) * MaxElement);

if(!S->Array)
printf("out of space\n");

S->Capacity = MaxElement;

MakeEmpty(S) ;


return S;
}


void DisposeStack(Stack S) //销毁栈
{
if( S != NULL)
{
free(S->Array);
free(S);
}
}


int IsEmpty(Stack S) //判空
{
return S->TopOfStack == EmptyTOS;
}


int IsFull(Stack S) //判满
{
return S->TopOfStack == S->Capacity;
}


void MakeEmpty(Stack S) //清空栈
{
S->TopOfStack = EmptyTOS;
}


void Push(ElementType X,Stack S) //入栈
{
if( IsFull(S) )
printf("Full Stack");
else
S->Array[++S->TopOfStack] = X;
}


ElementType Top(Stack S) //取栈顶元素
{
if( !IsEmpty(S))
return S->Array[S->TopOfStack];
else
{
printf("Empty Stack");
return 0;
}
}


void Pop(Stack S) //出栈
{
if(IsEmpty(S))
printf("Empty Stack\n");
else
S->TopOfStack--;
}


ElementType TopAndPop(Stack S) //出栈并取栈顶元素
{
if( !IsEmpty(S))
return S->Array[S->TopOfStack--];
else
{
printf("Empty Stack");
return 0;
}
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务