zoukankan      html  css  js  c++  java
  • LintCode "Expression Tree Build"

    Lesson learnt: for any calculator problems, keep 2 stacks: 1 for operators and 1 for operands.

    class Solution 
    {
        stack<ExpressionTreeNode*> op;
        stack<ExpressionTreeNode*> data;
        
        void eval()
        {
        ExpressionTreeNode *opnode = op.top(); op.pop();
        ExpressionTreeNode *data1 = data.top(); data.pop();
        ExpressionTreeNode *data2 = data.top(); data.pop();
        opnode->left = data2;
        opnode->right = data1;
        data.push(opnode);
        }
    public:
        ExpressionTreeNode* build(vector<string> &expression) 
        {
        for(auto &tmp : expression)
        {        
            ExpressionTreeNode *node = new ExpressionTreeNode(tmp);
             
            switch(tmp[0])
            {
            case '(':                         
                op.push(node);
                break;
            case '+':
            case '-':
                while(!op.empty()&&op.top()->symbol[0]!='(')
                {
                eval();
                }                         
                op.push(node);
                break;
            case '*':
            case '/':
                while(!op.empty()&&(op.top()->symbol[0]=='*'||op.top()->symbol[0]=='/'))
                {
                eval();
                }                         
                op.push(node);
                break;
            case ')':
                while(op.top()->symbol[0]!='(')
                {
                eval();
                }
                op.pop();
                break;
            default:
            data.push(node);
            break;
            }        
             }
             while(!op.empty())
         {
                 eval();
             }
             
             if(data.empty()) return nullptr;
             return data.top();
       }  
    };
  • 相关阅读:
    运算优先级
    (5).plus(3).minus(2);
    画图
    函数的三种角色
    表格排序
    正则表达式
    call apply
    css文本属性和边框属性
    css颜色/字体/背景属性
    css选择器优先级及继承
  • 原文地址:https://www.cnblogs.com/tonix/p/4891851.html
Copyright © 2011-2022 走看看