求解逆波兰表达式(Calculate the reverse Polish notation)。有关栈的最基础应用。

来源:互联网 发布:社会主义生产方式知乎 编辑:程序博客网 时间:2024/05/29 03:51

描述
编写函数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;} 
阅读全文
0 0