双栈实现算数表达式

来源:互联网 发布:在线制作手机淘宝店招 编辑:程序博客网 时间:2024/05/21 05:43

双栈算术表达式求值算法

源代码是java实现的,先把他改成cpp实现。

原理大家应该都懂,就是两个栈,一个保存读取式子的符号,遇到“(”不读,遇到“)”进行操作,其他符号保存。另一个栈保存每次读到的数字。

因为每次读到)时候,都要进行一次操作,而操作对象就是最小的那对括号里面的数字,也就是第二个栈顶保存的两个元素,所以可操作。

#include <iostream>#include <stack> #include <vector>#include <deque>#include <string>#include <math.h>#include<stdlib.h>#include<stdio.h>using namespace std;int main(){    stack<double> a;    stack<string> b;    string str;    while(cin>>str)//每次读入的时候遇到空格才会停下,所以每输入一个元素要输入一个空格,不知怎么解决。    {        if(str=="(");        else if(str=="+") b.push(str);        else if(str=="-") b.push(str);        else if(str=="*") b.push(str);        else if(str=="sqrt") b.push(str);        else if(str==")")        {            string op=b.top();            b.pop();// c++每次出栈不取出栈顶元素,所以每次要用top取完后在pop删除栈顶元素            double v=a.top();            a.pop();            if(op=="+")            {                v=a.top()+v;                a.pop();            }            else if(op=="-")            {                v=a.top()-v;                a.pop();            }            else if(op=="*")            {                v=a.top()*v;                a.pop();            }            else if(op=="sqrt")            {                v=sqrt(v);            }            a.push(v);        }        else        {            char c[20];            strcpy(c,str.c_str());            a.push(atof(c));//将string转换为double的函数atof只接受char*类型,所以上一步将string转换为char*        }    }    cout<<a.top();    }

0 0
原创粉丝点击