问题:逆波兰表达式又叫做后缀表达式。在通常的表达式中,二元运算符总是置于与之相关的两个运算对象之间,这种表示法也称为中缀表示
eg:
a+b ---> a,b,+
a+(b-c) ---> a,b,c,-,+
a+(b-c)*d ---> a,b,c,-,d,*,+
a+d*(b-c)--->a,d,b,c,-,*,+
a=1+3 ---> a=1,3 +
求:1 2 + 3 4 - * 答案:-3
用栈来做这道题...
求:1 2 + 3 4 - * 答案:-3
用栈来做这道题...
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int top,S[1000];
void push(int x){
S[++top] = x; //top+1后插入这个元素...
}
int pop(){
top--;
return S[top+1];//返回top所指的元素...
}
int main(){
int a,b,t=7;
top = 0; //清空栈...虽然这个时候数组里还有数...不过没关系..一会会覆盖掉...
char s[100];
freopen("1.txt","r",stdin);
while(scanf("%s",s) != EOF){
printf("%s\n",s);
if(s[0] == '+'){
a = pop();
b = pop();
push(a+b);
}
else if(s[0]=='-'){
b = pop();
a = pop();
push(a-b);
}
else if(s[0]=='*'){
a = pop();
b = pop();
push(a*b);
}
else{
push(atoi(s)); //atoi是把字符串转换成整型数值...
}
}
printf("%d\n",pop());
return 0;
}