【資料結構】棧實現表示式求值
阿新 • • 發佈:2019-01-09
用棧實現表示式求值,涉及到中、字尾表示式轉換的問題。
Expression.h
/*****************
* Calc_Expression()
* 功能: 利用棧實現整數表示式求值
* 輸入: 表示式字串
* 輸出: 求值結果
* 作者: wudi_X
* 日期: 2018-04-05
*******************/
#ifndef EXPRESSION_H_
#define EXPRESSION_H_
#include <iostream>
#include <string>
#include <stack>
#include <vector>
// -----------------將中綴表示式轉成字尾表示式-----------------
// 遍歷表示式,遇到運算元直接輸出,遇到操作符判斷棧頂優先順序
// 對於'+', '-'來說,優先順序最低,直接出棧直到棧空或者棧頂為'('
// 對於'*', '/', '('都直接壓入棧中
// 對於')',出棧直到遇到'('
static void Infix2Postfix(const std::string & strSrc, std::string & strDst) {
std::string output;
std::stack<char> s;
int i = 0;
while(i < strSrc.size()) {
char c = strSrc[i];
if (c == ' ')
continue;
if (c >= '0' && c <= '9') { // 讀取數字
output.push_back(c);
while (1) {
if (i == strSrc.size() - 1) {
output.push_back(' ' );
break;
}
if (strSrc[i + 1] >= '0' && strSrc[i + 1] <= '9') {
c = strSrc[++i];
output.push_back(c);
}
else {
output.push_back(' ');
break;
}
}
}
else if (c == '+' || c == '-') {
if (s.empty())
s.push(c);
else {
while (!s.empty() && s.top() != '(') {
output.push_back(s.top());
s.pop();
}
s.push(c);
}
}
else if (c == '*' || c == '/' || c == '(')
s.push(c);
else if (c == ')'){ // 處理右括號')'
while (s.top() != '(') {
output.push_back(s.top());
s.pop();
}
s.pop();
}
i++;
}
while (!s.empty()) {
output.push_back(s.top());
s.pop();
}
strDst = output;
}
int string2int(const std::string & str) {
int length = str.size();
int result = 0;
int mult = 1;
for (int i = length - 1; i >= 0; i--) {
char c = str[i];
result += (c - '0') * mult;
mult *= 10;
}
return result;
}
float Calc_Expression(const std::string & infix_str) {
// 轉換為字尾表示式.
std::string postfix_str;
Infix2Postfix(infix_str, postfix_str);
// 計算表示式.
std::stack<float> s;
for (int i = 0; i < postfix_str.size(); i++) {
char c = postfix_str[i];
if (c <= '9' && c >= '0') {
std::string digit_str;
digit_str.push_back(c);
while (1) {
c = postfix_str[++i];
if (c <= '9' && c >= '0') {
digit_str.push_back(c);
}
else if (c == ' '){
break;
}
}
float digit = float(string2int(digit_str));
s.push(digit);
}
else {
// 先從棧s取出2個運算元
float operand1 = s.top();
s.pop();
float operand2 = s.top();
s.pop();
switch (c)
{
case '+':
s.push(operand2 + operand1);
break;
case '-':
s.push(operand2 - operand1);
break;
case '*':
s.push(operand2 * operand1);
break;
case '/':
s.push(operand2 / operand1);
break;
default:
break;
}
}
}
return s.top();
}
#endif // EXPRESSION_H_
main.cpp
#include "expression.h"
int main() {
std::string a = "3*(1+1)-40/5";
float result = Calc_Expression(a);
std::cout << result << std::endl;
system("pause");
return 0;
}