#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define STACKSIZE 100
typedef int ElemType;
typedef struct
{
ElemType stack[STACKSIZE];
int top;
}SeqStack;
void InitStack(SeqStack *S)//将栈S初始化为空栈
{
S->top = 0;
}
int StackEmpty(SeqStack S)//判断栈是否为空,栈为空返回1,否则返回0
{
if(0 == S.top)
{
return 1;
}
else
{
return 0;
}
}
int GetTop(SeqStack S,ElemType *c)//取栈顶元素,将栈顶元素值返回给e,并返回1表示成功,返回0表示失败
{
if(S.top <= 0)
{
printf("栈已经空!\n");
return 0;
}
else
{
*c = S.stack[S.top-1];//取栈顶元素
return 1;
}
}
int PushStack(SeqStack *S,ElemType c)//进栈操作
//将元素e进栈,元素进栈成功返回1,否则返回0
{
if(S->top >= STACKSIZE-1)
{
printf("栈已满,不能入栈!");
return 0;
}
else
{
S->stack[S->top] = c;
S->top++;
return 1;
}
}
int PopStack(SeqStack *S,ElemType *c)//出栈操作
{
if(S->top <= 0)
{
printf("栈已经没有元素,不能出栈!\n");
return 0;
}
else
{
S->top--;
*c = S->stack[S->top];
return 1;
}
}
int StackLength(SeqStack S)//返回栈长度
{
return S.top;
}
void ClearStack(SeqStack *S)//清空栈
{
S->top = 0;
}
//#include "顺序栈.h"
/将元素a,b,c,d,e依次入栈,然后将d和e出栈,再将f和g进栈,最后将元素全部进栈,并将元素按照出栈次序输出/
int main(void)
{
SeqStack S;
int i;
ElemType a[] = {'a','b','c','d','e','f','g'};
ElemType e;
InitStack(&S);
for(i = 0;i < sizeof(a)/sizeof(a[0]);i++)
{
if(PushStack(&S,a[i]) == 0)
{
printf("栈已满,不能进栈!");
return 0;
}
}
printf("出栈元素是:");
if(PopStack(&S,&e) == 1)
{
printf("%4c",e);
}
if(PopStack(&S,&e) == 1)
{
printf("%4c",e);
}
printf("\n");
printf("当前栈顶元素是:");
if(GetTop(S,&e) == 0)
{
printf("栈已空!");
return 0;
}
else
{
printf("%4c\n",e);
}
if(PushStack(&S,'e') == 0)
{
printf("栈已满,不能进栈!");
return 0;
}
if(PushStack(&S,'d') == 0)
{
printf("栈已满,不能进栈!");
return 0;
}
printf("当前栈的元素个数是:%d\n",StackLength(S));
printf("元素的出栈顺序是:");
while(!StackEmpty(S))
{
PopStack(&S,&e);
printf("%4c",e);
}
printf("\n");
return 0;
}