C++实现逆波兰式

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C++实现逆波兰式

Who_Am_I.   2020-11-01 我要评论

(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;
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们