Shunting-yard dispatch field algorithm, infix expression inversion Polish expression

Source: Internet
Author: User
Tags string to number

infix expression

1* (2+3)

This is an infix expression, operators between numbers, computer processing prefix expressions and suffix expressions is easier, but processing infix expressions is not easy, so we need to use Shunting-yard algorithm (dispatch field algorithm) to convert infix expression to a suffix expression ( i.e. inverse Polish expression), then solve.

The above infix expression goes to the suffix expression after:

1 2 3 + *

scheduling field Algorithm

In order to convert infix expression to suffix expression, using the Scheduling field algorithm, the idea of the algorithm is as follows:

Prepare two stacks, one for storing numbers, and one for storing operators.

The expression is traversed from left to right and, if it is a number, directly into the stack. (Note that the number may be multi-digit or even decimal)

If it is a symbol:

If the stack is empty, or the current symbol is ' (', or the top of the stack is ' ('), directly into the stack.

If the current operator precedence is higher than the precedence of the top of the stack operator, the stack is entered. (note is above, equal to also not)

If the current operator priority is not higher than the top of the stack operator, first remove an operator from the stack of stored symbols, remove two numbers from the stack of stored data, do one operation and press the result into the data stack , and finally press the current operator into the symbol stack.

If the current symbol is ') ', repeat the operation of the underlined section until the operator is ' (').

After the expression has been traversed, the operation of the underlined part is repeated until the symbol stack is empty, and there is a number in the data stack, which is the value of the original expression.

This is basically done.

Here again to discuss the handling of the negative sign, how to determine '-' is the minus or negative?

If '-' appears at the beginning of an expression, it must be a minus sign.

If '-' appears behind the number, it must be a minus sign.

If '-' appears after ' (', must be minus.

If '-' appears ' behind ', it must be a minus sign.

As can be seen, as long as '-' at the beginning of the expression or ' (' can be judged as a minus, but how to deal with after the judgment?

There are two ways, one is to judge the negative sign when the number 0 is pressed into the data stack, and then press the minus sign into the symbol stack, can be seen as 0 minus a number.

Alternatively, if the negative sign is judged, multiply the next number that is pressed into the data stack by 1. In this way it is important to note that if there is only one negative in the parentheses and no formula, then the next ') ' will be pressed directly into the stack, causing strange things to happen, as long as the ') ' is in the stack before you can avoid this problem. (The following code takes the second method)

C + + code is implemented as follows

#include <iostream>#include<string>#include<cstring>#include<stack>using namespacestd;intop[ -];//determining the precedence of an operator/*string to number*/DoubleTodig (stringstr) {    Doublen =0, mag =0.1;  for(inti =0; I < str.length (); i++) {        if(str[i]=='.') Break; Mag*=Ten; }     for(inti =0; I < str.length (); i++) {        if(str[i]=='.')Continue; N+ = mag* (Str[i]-'0'); Mag/=Ten; }    returnN;}/*Calculate and return results*/DoubleGetans (DoubleADoubleBCharc) {Switch(c) { Case '+':returnB +A;  Case '-':returnB-A;  Case '*':returnb*A;  Case '/':returnb/A; }}/*Shunting-yard*/DoubleShunting (stringstr) {Stack<Double>Istk; Stack<Char>Strstk;  for(inti =0; I <str.length ();) {        if((str[i]>='0'&& str[i]<='9') || (i==0&&str[i]=='-') || (str[i]=='-'&&str[i-1]=='(')) {            //determine whether a number or minus sign            stringS1; intf =1; if(str[i]=='-') {f=-1; I++; }             while((str[i]>='0'&& str[i]<='9') || str[i]=='.') {S1+ = str[i++]; } Istk.push (f*Todig (S1)); } Else{//is not a number or minus sign, it is an operator or parenthesis//if the stack is empty, or the operator is ' (', or the top of the stack is ' ('), or the current operator is greater than the top operator, the operator is in the stack            if(Strstk.empty () | | str[i]=='('|| Strstk.top () = ='('|| (str[i]!=')'&&op[str[i]] >op[strstk.top ()])) {                if(str[i]==')'&& strstk.top () = ='(') Strstk.pop ();//the current symbol and the top of the stack are a pair of parentheses to eliminate them                ElseStrstk.push (Str[i]); }            Else if(Str[i] = =')') {                //if current is ') ', then do the operation until the top of the stack is ' ('                Charc =Strstk.top ();  while(c! ='(') {                    DoubleA =Istk.top ();                    Istk.pop (); Doubleb =Istk.top ();                    Istk.pop ();                    Strstk.pop ();                    Istk.push (Getans (a,b,c)); C=Strstk.top ();            } strstk.pop (); }            Else {                //Otherwise, the current operator precedence is equal to or less than the top of the stack operator, the top operator of the stack is taken out for one operation, the result of the operation is stacked, and the current operator is then put into the stack                DoubleA =Istk.top ();                Istk.pop (); Doubleb =Istk.top ();                Istk.pop (); Charc =Strstk.top ();                Strstk.pop ();                Istk.push (Getans (a,b,c));            Strstk.push (Str[i]); } I++; }    }    //after the expression has been processed, the computation continues until the operator is empty, and the rest of the data stack is the final result.     while(!Strstk.empty ()) {        DoubleA =Istk.top ();        Istk.pop (); Doubleb =Istk.top ();        Istk.pop (); Charc =Strstk.top ();        Strstk.pop ();    Istk.push (Getans (a,b,c)); }    returnistk.top ();}intMain () {strings; Memset (OP,1,sizeof(OP)); op['+'] = op['-'] =0; op['*'] = op['/'] =1;  while(Cin >>s) {cout<< shunting (s) <<Endl; }    return 0;}

Shunting-yard dispatch field algorithm, infix expression inversion Polish expression

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.