標題:逆波蘭表達式
正常的表達式稱爲中綴表達式,運算符在中間,主要是給人閱讀的,機器求解並不方便。
例如:3 + 5 * (2 + 6) - 1
而且,常常需要用括號來改變運算次序。
相反,如果使用逆波蘭表達式(前綴表達式)表示,上面的算式則表示爲:
-
- 3 * 5 + 2 6 1
不再需要括號,機器可以用遞歸的方法很方便地求解。
爲了簡便,我們假設:
- 只有 + - * 三種運算符
- 每個運算數都是一個小於10的非負整數
下面的程序對一個逆波蘭表示串進行求值。
其返回值爲一個結構:其中第一元素表示求值結果,第二個元素表示它已解析的字符數。
struct EV
{
int result; //計算結果
int n; //消耗掉的字符數
};
struct EV evaluate(char* x)
{
struct EV ev = {0,0};
struct EV v1;
struct EV v2;
if(*x==0) return ev;
if(x[0]>='0' && x[0]<='9'){
ev.result = x[0]-'0';
ev.n = 1;
return ev;
}
v1 = evaluate(x+1);
v2 = _____________________________; //填空位置
if(x[0]=='+') ev.result = v1.result + v2.result;
if(x[0]=='*') ev.result = v1.result * v2.result;
if(x[0]=='-') ev.result = v1.result - v2.result;
ev.n = 1+v1.n+v2.n;
return ev;
}
請分析代碼邏輯,並推測劃線處的代碼,通過網頁提交。
注意:僅把缺少的代碼作爲答案,千萬不要填寫多餘的代碼、符號或說明文字!!
#include <iostream>
#include <cstring>
using namespace std;
struct EV {
int result; //計算結果
int n; //消耗掉的字符數
};
struct EV evaluate(char *x) {
struct EV ev = {0, 0};
struct EV v1;
struct EV v2;
if (*x == 0) return ev;
if (x[0] >= '0' && x[0] <= '9') {
ev.result = x[0] - '0';//字符轉數字'1'-'0'=1
ev.n = 1;
return ev;
}
//- + 3 * 5 + 2 6 1
v1 = evaluate(x + 1);
v2 = evaluate(x + 1 + v1.n); //填空位置
if (x[0] == '+') ev.result = v1.result + v2.result;
if (x[0] == '*') ev.result = v1.result * v2.result;
if (x[0] == '-') ev.result = v1.result - v2.result;
ev.n = 1 + v1.n + v2.n;
return ev;
}
int main(int argc, const char * argv[]) {
string s="-+3*5+261";
const EV &ev = evaluate((char*)(s.c_str()));
cout<<ev.result<<endl;
return 0;
}