后缀表达式求值(顺序栈)

来源:互联网 发布:淘宝工厂店怎么开 编辑:程序博客网 时间:2024/06/04 18:42
#include<iostream>#include<malloc.h>#define MAXSIZE50using namespace std;typedef int DataType;typedef struct{DataType data[MAXSIZE];int top;}SeqStack,* PSeqStack;int main(){//函数声明PSeqStack Init_SeqStack(void);/*建空栈*/void Push_SeqStack(PSeqStack S,DataType x);/*入栈*/int Empty_SeqStack(PSeqStack S);/*判断栈是否为空*/void Pop_SeqStack(PSeqStack S,DataType * y);/*出栈*/int GetTop_SeqStack(PSeqStack S);/*取栈顶元素*/void Destroy_SeqStack(PSeqStack * S);/*销毁栈*/int IsNum(char c);/*判断字符是否为操作数*/int postfix_exp(char * A);/*后缀表达式求值*/char a[]="1285-*+42/-#";//后缀表达式cout<<postfix_exp(a);//计算结果return 0;}/*建空栈*/PSeqStack Init_SeqStack(void){PSeqStack S;S=(PSeqStack)malloc(sizeof(SeqStack));if(S){S->top = -1;//表示空栈}return S;}/*入栈*/void Push_SeqStack(PSeqStack S,DataType x){if(S->top == (MAXSIZE-1)){cout<<"栈满不能入栈!";}else{S->top++;S->data[S->top]=x;}}/*判断栈是否为空*/int Empty_SeqStack(PSeqStack S){if(S->top == -1)return 1;elsereturn 0;}/*出栈*/void Pop_SeqStack(PSeqStack S,DataType * y){if(Empty_SeqStack(S)){cout<<"栈空不能出栈!";}else{* y=S->data[S->top];S->top--;}}/*取栈顶元素*/int GetTop_SeqStack(PSeqStack S){if(Empty_SeqStack(S)){return 0;}return S->data[S->top];}/*销毁栈*/void Destroy_SeqStack(PSeqStack * S){if(* S)free(* S);* S=NULL;}/*判断字符是否为操作数*/int IsNum(char c){if(c>='0' && c<='9')return 1;elsereturn 0;}/*后缀表达式求值*/int postfix_exp(char * A){int a,b,c;char ch=*A++;PSeqStack S=Init_SeqStack();while(ch != '#'){if(IsNum(ch))//若是操作数Push_SeqStack(S,ch-48);//ch-48变整数,存入栈中else{Pop_SeqStack(S,&b);Pop_SeqStack(S,&a);switch(ch){case '+':c=a+b;break;case '-':c=a-b;break;case '*':c=a*b;break;case '/':c=a/b;break;case '%':c=a%b;break;}Push_SeqStack(S,c);//计算结果存入栈}ch=*A++;//下个字符}int result=GetTop_SeqStack(S);//取最终结果Destroy_SeqStack(&S);//销毁栈return result;}

0 0
原创粉丝点击