[C++]求表达式的逆波兰式
Posted HiveDark
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[C++]求表达式的逆波兰式相关的知识,希望对你有一定的参考价值。
// ReversePolish2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <string>
#include <stack>
using std::cout;
using std::cin;
using std::endl;
using std::stack;
using std::string;
int priority(char c)
switch (c)
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
default:
return 0;
template<class T> string printStack(stack<T> stack)
string result = "";
while (!stack.empty())
result = stack.top()+result;
stack.pop();
return result;
string reversePolish(string inputStr)
stack<char> polish;
stack<char> opStack;
bool lastIsNum = false;
for (int i = 0; i < inputStr.length(); i++)
char curChar = inputStr.at(i);
//如果是数字
if (curChar >= '0' && curChar <= '9')
if (!lastIsNum)
polish.push(' ');
polish.push(curChar);
lastIsNum = true;
continue;
//否则为操作符
else if (curChar == '(')
opStack.push(curChar);
else if (!opStack.empty() && curChar == ')')
while (opStack.top() != '(')
polish.push(opStack.top());
opStack.pop();
opStack.pop();
else
if (!opStack.empty() && opStack.top() == '(')
opStack.push(curChar);
else
if (!opStack.empty() && priority(curChar) > priority(opStack.top()))
opStack.push(curChar);
else
while (!opStack.empty())
if (opStack.top() == '(')
break;
if (priority(curChar) <= priority(opStack.top()))
polish.push(opStack.top());
opStack.pop();
else
break;
opStack.push(curChar);
lastIsNum = false;
while (!opStack.empty())
polish.push(opStack.top());
opStack.pop();
return printStack(polish);
int main()
string str;
cout << "请输入表达式: ";
cin>>str;
string result = reversePolish(str);
cout << result<< endl;
system("pause");
return 0;
数字之间以空格隔开以便于下一步计算表达式的值
以上是关于[C++]求表达式的逆波兰式的主要内容,如果未能解决你的问题,请参考以下文章