C++实现逆波兰式

(a+b)c的逆波兰式为ab+c,假设计算机把ab+c按从左到右的顺序压入栈中,并且按照遇到运算符就把栈顶两个元素出栈,执行运算,得到的结果再入栈的原则来进行处理,那么ab+c的执行结果如下:

1)a入栈(0位置)2)b入栈(1位置)3)遇到运算符“+”,将a和b出栈,执行a+b的操作,得到结果d=a+b,再将d入栈(0位置)4)c入栈(1位置)5)遇到运算符“”,将d和c出栈,执行dc的操作,得到结果e,再将e入栈(0位置)

经过以上运算,计算机就可以得到(a+b)*c的运算结果e了。

逆波兰式除了可以实现上述类型的运算,它还可以派生出许多新的算法,数据结构,这就需要灵活运用了。逆波兰式只是一种序列体现形式。

eg:

输入示例

1 2 + 3 4 – *

输出示例

-3

代码

#include <iostream>#include <stack>#include <cstdio>using namespace std;int main(){ string s; getline(cin,s); int n = s.length();//字符串长度 stack<int> t; for(int i=0;i<n;i++) { char c=s[i]; if(c=='+'){ int a=t.top(); t.pop(); int b=t.top(); t.pop(); t.push(a+b); } else if(c=='-'){ int a=t.top(); t.pop(); int b=t.top(); t.pop(); t.push(b-a); } else if(c=='*'){ int a=t.top(); t.pop(); int b=t.top(); t.pop(); t.push(a*b); } else if(c=='/'){ int a=t.top(); t.pop(); int b=t.top(); t.pop(); t.push(a/b); } else if(c==' '){ continue; } else{//数字 int m=(int)c; m=m-48; t.push(m); } } cout<<t.top(); return 0;}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

只有流过血的手指才能弹出世间的绝唱。

C++实现逆波兰式

相关文章:

你感兴趣的文章:

标签云: