求解逆波蘭表示式(Calculate the reverse Polish notation)。有關棧的最基礎應用。
阿新 • • 發佈:2019-01-29
描述
編寫函式int add(char s[]);計算字串形式的逆波蘭表示式(即兩個運算元在前,計算符在後)。本題內,保證每個運算元均為1位數。操作符有’+’,’-‘,’*’,’/’四種。且保證計算過程中除法運算全部為整數除法,結果為整數。
如23+4*,,結果20
Write a function int add (char s []); Calculate the string form of reverse Polish notation (ie, the first is two operands, then the operator). This problem, to ensure that each of the operands are 1-digit. The operator have only four: ‘+’, ‘-‘, ‘*’, ‘/’. And to ensure that the division operation in the calculation process for all the integer division, the result is an integer.
Such as 23+4*, the result is 20.
輸入
一行字串,長度不超過20。
Input a string, no more then 20 characters.
輸出
逆波蘭表示式的計算結果。
Output the result of reverse Polish notation.
輸入樣例
23+4*
輸出樣例
20
#include<iostream>
#include<stack> //棧的標頭檔案
using namespace std;
stack <int> s1; //宣告一個棧
int calcu(int n1,int n2,char op)
{
int result;
if(op=='+') result=n1+n2;
else if(op=='-') result=n1-n2;
else if(op=='*') result=n1*n2;
else result=n1/n2;
return result;
}
int main()
{
char s[1000];
cin>>s;
int i=0,num1,num2,result;
while(s[i])
{
if(s[i]>=48&&s[i]<=57)
{
s1.push(s[i]-'0');//如果是數字則向棧中壓入一個數字
result=s1.top();
/*如果字串中一個數字(沒有運算子),則把這個數字當作結果輸出。
這是一個數據陷阱,如果沒有這條語句,這種情況下輸出的result是任意值。*/
}
else//在遇到運算子時
//棧中現在應該有先輸入的資料num1和後輸入的資料num2。
{
num2=s1.top();
//因為棧中的資料是後進先出的,在棧頂的是剛剛輸入的資料num2。
//不能顛倒num1和num2的順序,否則在減和除運算時會出現錯誤。
s1.pop();//從棧頂彈出一個成員num2,棧中只剩num1。
num1=s1.top();
s1.pop();//現在棧是空的
result=calcu(num1,num2,s[i]);
//計算num1和num2的運算結果
s1.push(result);//將結果壓入棧中,成為下一次運算的num1.
}
i++;
}
cout<<result<<endl;
}