/*
*数据结构(栈):顺序栈
*栈为空时,栈顶指针top==-1;栈不为空时,top==栈顶元素数组下表+1
*top != 0; top > 0时,表示栈中元素个数;
*Date:2017/4/14
*/
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 50
#define ElemType char
typedef struct{
ElemType data[MaxSize]; //用静态数组模拟顺序栈
int top; //栈顶指针
}SqStack;
void initStack(SqStack &S); //初始化顺序栈
ElemType getTop(SqStack S); //取栈顶元素
void push(SqStack &S,ElemType e); //进栈
void pop(SqStack &S,ElemType *e); //出栈
bool emptyStack(SqStack S); //判断栈S是否为空,若为空则返回true,否则返回false
void destroyStack(SqStack &S); //销毁栈S
void initStack(SqStack &S){
char ch;
S.top = -1; //空栈,栈顶指针==-1
while(scanf("%c",&ch) != EOF && ch != '\n'){
if(S.top == -1){
S.top = 0;
}
S.data[S.top++] = ch;
}
}
ElemType getTop(SqStack S){
return S.data[S.top-1];
}
void push(SqStack &S,ElemType e){
S.data[S.top++] = e;
}
void pop(SqStack &S,ElemType *e){
*e = S.data[--S.top];
}
bool emptyStack(SqStack S){
if(S.top == -1){
return true;
}else{
return false;
}
}
void destroyStack(SqStack &S){
S.top = -1;
}
int main(){
freopen("in.txt","r",stdin);
SqStack S;
ElemType e;
initStack(S);
printf("getTop(S):%c\n",getTop(S));
pop(S,&e);
printf("pop(S,&e):%c\n",e);
printf("getTop(S):%c\n",getTop(S));
push(S,'p');
printf("push(S,'p'):%c\n",getTop(S));
if(emptyStack(S)){
printf("S is NULL\n");
}else{
printf("S isn't NULL\n");
}
destroyStack(S);
printf("destroyStack(S):\n");
if(emptyStack(S)){
printf("S is NULL\n");
}else{
printf("S isn't NULL\n");
}
return 0;
}
in.txt:
orange