逆波兰表示法是一种将运算符(operator)写在操作数(operand)后面的描述程序(算式)的方法。举个例子,我们平常用中缀表示法描述的算式(1 + 2)*(5 + 4),改为逆波兰表示法之后则是1 2 + 5 4 + *。相较于中缀表示法,逆波兰表示法的优势在于不需要括号。
请输出以逆波兰表示法输入的算式的计算结果。
输入格式:
在一行中输入1个算式。相邻的符号(操作数或运算符)用1个空格隔开。
输出格式:
在一行中输出计算结果。
限制:
2≤算式中操作数的总数≤100
1≤算式中运算符的总数≤99
运算符仅包括“+”、“-”、“*”,操作数、计算过程中的值以及最终的计算结果均在int范围内。
输入样例1:
4 3 + 2 -
输出样例1:
5
输入样例2:
1 2 + 3 4 - *
输出样例2:
-3
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 199struct SNode{int Data[MaxSize];int Top;
};
typedef struct SNode *Stack;Stack CreateStack(){Stack p;p=(Stack)malloc(sizeof(struct SNode));p->Top=-1;return p;
}void Push(Stack S,int x){if(S->Top==MaxSize){printf("Stack Full\n");}else{S->Data[++S->Top]=x;}
}int Pop(Stack S){if(S->Top==-1){printf("Stack is Empty!\n");}else{int t;t=S->Data[S->Top];S->Top--;return t;}
}int main(){Stack S;S=CreateStack();char ch;ch=getchar();int a,b,an,t;while(ch!=EOF){if(ch>='0'&&ch<='9'){Push(S,ch-'0');ch=getchar();while(ch>='0'&&ch<='9'){t=Pop(S);Push(S,t*10+ch-'0');ch=getchar();}}else if(ch=='+'||ch=='-'||ch=='*'){a=Pop(S);b=Pop(S);switch(ch){case '+':an=b+a;break; case '-':an=b-a;break; case '*':an=b*a;break;}Push(S,an);}else if(ch=='\n'){break;}ch=getchar();}printf("%d",Pop(S));
}