/**
* 作者: LinX 2017-6-15
*
* 内容: 顺序栈的结构以及基本操作
*
*/
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef int ElemType;
typedef struct SqStack
{
ElemType data[MAXSIZE];
int top;
}SqStack;
/*栈的基本操作*/
SqStack* InitStack(); //初始化栈
void push(SqStack *S,ElemType e); //压栈
ElemType pop(SqStack *S); //弹栈
int stackEmpty(SqStack *S); //判空
int stackFull(SqStack *S); //判满
void printStack(SqStack *S); //打印栈中元素
int main()
{
SqStack *S = InitStack();
push(S,1);
push(S,2);
push(S,3);
push(S,4);
printStack(S);
printf("%d ",pop(S));
printf("%d ",pop(S));
printf("%d ",pop(S));
printf("%d ",pop(S));
printf("%d",pop(S));
printf("%d",pop(S));
return 0;
}
/*初始化栈*/
SqStack* InitStack()
{
SqStack *S = (SqStack *) malloc (sizeof(SqStack));
S->top = -1;
return S;
}
/*压栈*/
void push(SqStack *S,ElemType e)
{
if(stackFull(S)==1)
{
printf("\n栈满\n");
return;
}
S->data[++S->top] = e;
}
/*弹栈*/
ElemType pop(SqStack *S)
{
ElemType e;
if(stackEmpty(S)==1)
{
printf("\n栈空\n");
return -1;
}
e=S->data[S->top--];
return e;
}
/*打印栈中元素*/
void printStack(SqStack *S)
{
if(stackEmpty(S) == 1)
{
printf("\n栈空\n");
return;
}
int i;
for(i = 0;i<=S->top;i++)
printf("%d ",S->data[i]);
printf("\n");
}
/*判空*/
int stackEmpty(SqStack *S)
{
if(S->top == -1)
return 1;
return 0;
}
/*栈满*/
int stackFull(SqStack *S)
{
if(S->top == MAXSIZE - 1)
return 1;
return 0;
}
栈的结构及其操作
最新推荐文章于 2022-03-01 13:10:27 发布