问题来源http://hi.baidu.com/frankxieke/item/d8536acf63e1a57f89ad9eb8
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef char Status;
typedef char SElemType;
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
Status InitStack(SqStack &S){
S.base = (SElemType * )malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!S.base) exit(OVERFLOW);
S.top = S.base;
S.stacksize=STACK_INIT_SIZE;
return OK;
}//InintStack
Status GetTop(SqStack S,SElemType &e){
if(S.top==S.base) return ERROR;
e=*(S.top-1);
return OK;
}//GrtTop
Status Push(SqStack &S,SElemType e){
if(S.top-S.base>=S.stacksize){
S.base=(SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));
if(!S.base) exit(OVERFLOW);
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top++=e;
return OK;
}//Push
Status Pop(SqStack &S,SElemType &e){
if(S.top==S.base) {e = -1;return ERROR;}
e=*--S.top;
return OK;
}//Pop
Status ClearStack(SqStack &S){
S.top=S.base;
return OK;
}//ClearStack
Status DestroyStack(SqStack &S){
S.top=0;
return OK;
}
void LineEdit(){
SqStack S;
InitStack(S);
char ch;
ch=getchar();
while(ch!=EOF){
while(ch!=EOF&&ch!='\n'){
switch(ch){
case '#':
{
Pop(S,ch);
if(ch != -1)
cout << "pop success: " << ch << endl;
else
cout << "pop error : stack empty " << endl;
break;
}
case '@':
{
ClearStack(S);
cout << "clear success" << endl;
break;
}
default :
{
Push(S,ch);
cout << "push success: " << ch << endl;
break;
}
}
ch=getchar();
}
if(S.top != 0)ClearStack(S);
ch = getchar();
}
DestroyStack(S);
}
int main()
{
LineEdit();
return 0;
}