Calculator core algorithm - infix expression into postfix notation

Infix expression during rotation postfix expression is similar to the compilation process
- four in an arithmetic expression parentheses must match
- converted according to operator precedence
- no expression in brackets after the conversion
- after conversion can be sequential calculate the final result

This is an algorithm developed by a great man, where we can be directly used.

Conversion process:
- e is the current element number: Output
- e is the current element Operators:
1. the top of the stack operator priority comparing
2 or less: the output of the top element, a transfer
3. greater than: the e current element stack

- e to the left of the current element parenthesis: Drawing
- e is the current element Right parenthesis:
1. pop the top element and outputs, to the left bracket until the top element
2. The top of the stack is popped from the left parenthesis stack

the while (! exp.isEmpty ()) 
{ 
    QString S = exp.dequeue (); 
    
    IF (isNumber (E)) 
        output E; 
    the else  IF (isOperator (E)) 
    { 
        the while (priority (E) <= priority (Stack. Top ())) 
            output stack elements: stack.pop (); 
            
        stack.push (E); 
    } 
    the else  IF (isLeft (E)) 
        stack.push (E); 
    the else  IF (isRight (E)) 
    { 
        the while ( ! isLeft (stack.top ())) 
            output of the top element stack.pop (); 
            
        pop from the stack left parenthesis: stack.pop (); 
    } 
}

exp is a blog post with a separate queue algorithm, each dollar count are handled inside, that has been processed to date this queue is empty.

关键点:转换过程中左右括号是重要标志
——如何确保表达式中的括号能够左右匹配?

合法的四则运算表达式
——括号匹配成对出现
——左括号必然先于右括号出现

for(int i=0; i<len; i++)
{
    if(exp[i]为左括号)
        exp[i]入栈;
    else if(exp[i]为右括号)
    {
        if(栈顶元素为左括号)
            将栈顶元素弹出;
        else    
            匹配错误
    }
}

 

Guess you like

Origin www.cnblogs.com/-glb/p/12104939.html