从键盘上输入一个算数表达式,试编写算法,计算出该表达式的逆波兰表达式。规定:逆波兰表达式的长度不超过一行,以$符作为输入结束,操作数之间用空格分隔,操作符只可能有+、-、、/四种运算。(注释要详细)
例1:输入为:2+3$,输出逆波兰表达式为:2 3 +。
例2:输入为:23$,输出逆波兰表达式为:2 3 。
例3:输入为:1+23$,输出逆波兰表达式为:1 2 3 * +。
例4:输入为:(1+2)3$,输出逆波兰表达式为:1 2 + 3 。
例5:输入为:(1+23)4$,输出逆波兰表达式为:1 2 3 * + 4 。
例6:输入为:6((5+(2+3)*8)+3)$,输出逆波兰表达式为:6 5 2 3 + 8 * + 3 + *。
提示1:括号成对,输出运算符;否则,输出数字。
提示2:求逆波兰表达式规则如下:设立运算数栈OPND,对表达式从左到右扫描(读入),当表达式中扫描到数时,压入OPND栈。当扫描到运算符时,从OPND退出两个数,进行相应运算,结果再压入OPND栈。这个过程一直不断运行直至表达式结束符$。
#include <iostream>
#include <stack>
#include <string>
using namespace std;
// 运算符优先级,数值越大,优先级越高
int priority(char c)
{
if (c == '+' || c == '-')
return 1;
else if (c == '*' || c == '/')
return 2;
else
return 0;
}
int main()
{
// 运算数栈
stack<int> opnd;
// 运算符栈
stack<char> optr;
char c;
cin >> c;
while (c != '$')
{
// 如果是数字,直接输出
if (isdigit(c))
cout << c << ' ';
else if (c == '(')
optr.push(c);
else if (c == ')')
{
while (optr.top() != '(')
{
cout << optr.top() << ' ';
optr.pop();
}
optr.pop(); // 将'('弹出但不输出
}
else
{
// 如果当前运算符的优先级小于等于栈顶运算符的优先级,则将栈顶运算符弹出并输出
while (!optr.empty() && priority(c) <= priority(optr.top()))
{
cout << optr.top() << ' ';
optr.pop();
}
optr.push(c);
}
cin >> c;
}
// 将剩余的运算符依次弹出并输出
while (!optr.empty())
{
cout << optr.top() << ' ';
optr.pop();
}
return 0;
}
# include<iostream>
# include<stack>
# include<stdlib.h>
# include<string>
using namespace std;
# include<iostream>
# include<stack>
# include<stdlib.h>
using namespace std;
//声明
bool IsOpreator(const char *op);
int ReversePoli(const char *str[], int len);
//判断是否操作符
bool IsOpreator(const char *op)
{
return ((op[0] == '+') || (op[0] == '-') || (op[0] == '*') || (op[0] == '/'));
}
//定义逆波兰表达式
int ReversePoli(const char *str[], int len)
{
int a, b;
const char *p;
stack<int> s;
for (int i = 0; i < len; i++)
{
p = str[i];
if (!IsOpreator(p))
{
s.push(atoi(p));
}
else
{
a = s.top();
s.pop();
b = s.top();
s.pop();
if (p[0] == '+')
s.push(a + b);
if (p[0] == '-')
s.push(a - b);
if (p[0] == '*')
s.push(a * b);
if (p[0] == '*')
s.push(a * b);
if (p[0] == '/')
s.push(a / b);
}
}
return s.top();
}
int main()
{
const char *str[] = { "2","1","+","3","*" };
int len = sizeof(str)/sizeof(const char*);
int result = ReversePoli(str, len);
cout << result << endl;
}