C + + suffix expression (inverse polish) for four expression value, using Stack in STL

Source: Internet
Author: User

Introduction:

The 1950s, Polish logic home Janlukasiewicz, thought of a suffix expression that does not need parentheses, we also call it inverse Polish (Reverse Polish Notation, RPN), for "such as 9 + (3-1) X3 +10-/2 "If the suffix notation should be:" 9 3 1-3*+10 2/+ ", such an expression is called a suffix expression.

infix expression-to-suffix expression rules:

Each number and symbol of the infix expression is traversed from left to right, and if the number is output, it becomes part of the suffix expression, and if the symbol is the priority of the symbol, it is the right parenthesis or priority lower than the top of the stack (multiplication precedence plus minus), the top element of the stack is sequentially out of the stack and the current symbol is Until the final output suffix expression.

The suffix expression evaluates:

From left to right to iterate through the expression of each number and symbol, encountered is the number on the branch, encountered is a symbol, will be in the top of the orange two numbers out, the operation, the results of the operation into the money, until the final results obtained.

example code:
<pre name= "code" class= "CPP" >//=========================================================================== =//name:sizecal.cpp//author:guo//version:0.1//copyright:nupt//Description: Arithmetic expression evaluation, input integer Arithmetic an expression to evaluate its value. PS: This version does not support a space in the input! ============================================================================ #include <iostream> #include <stack>//use stl#include <stdio.h> #include <string.h> #include <stdlib.h>using namespace std; const int Maxsize=256;int infixtopostfix (char *infix,char *postfix);d ouble Calculate (char *arr); int main () {cout < < "arithmetic, enter the expression:" << Endl; Prints arithmetic char in[maxsize]={0};char postfix[maxsize]={' + '};fgets (In,maxsize,stdin); if (Infixtopostfix (in, postfix)!=1) {cout<< "infixtopostfix wrong!!!"; return-1;} Puts (in);p UTS (postfix); cout<<calculate (postfix); return 0;} /* Convert infix expression to suffix expression argument: infix points to infix expression, ending with enter. Postfix points to the suffix expression temporary buffer, which holds the converted result. With conversion rules: from left to right, each number and symbol of the infix expression is traversed, and if the number is stored directly in the postfix arrayIn the case of symbols, it is determined that the priority of the top of the stack, is the right parenthesis or priority is not greater than the top of the stack symbol, then the stack top element sequentially out of the stack and output, until the opening parenthesis or stack empty, the symbol just before it into the stack.  */int Infixtopostfix (char *infix,char *postfix) {stack<char> s;  Char c,e;  int j=0,i=0; c=* (Infix+i);  Remove the first character in the infix expression i++;       while (' \ n '!=c)//encounters a newline character that represents the end of the conversion {while (c>= ' 0 ' &&c<= ' 9 ')///first determine if the character being taken is a number, or if it is a number, it is directly deposited in the postfix array          {postfix[j++]=c;          c=* (Infix+i);          i++; if (c< ' 0 ' | |            C> ' 9 ')//If it is not a number, add a space later to distinguish the symbols {postfix[j++]= '; }} if (') ' ==c)//is not a number, then the right parenthesis is judged.      [The parentheses have the highest precedence, so if it's a closing parenthesis, you'll have to perform the various operations in parentheses first]          {e=s.top (); S.pop ();             while (' ('!=e)//until the opening parenthesis is encountered {postfix[j++]=e;             Postfix[j++]= ";          E=s.top (); S.pop (); }} else if (' + ' ==c| | ' -' ==c ')//if it is plus minus, because they have the lowest priority, so at this time all the symbols in the stack after the stack (unless you encounter an opening parenthesis), then put this symbol in the stack {if (!          S.size ()))//If it is an empty stack, add the minus sign directly into the stack {s.push (c); } else//If it is not an empty stack, first take all the precedence above the plus minus stack, and then add theInto the stack {do{e=s.top (); S.pop ();                  if (' (' ==e) {s.push (e);                    } else {postfix[j++]=e;                  Postfix[j++]= ";  }}while (S.size () && ' ('!=e); Stack all symbols in the stack (unless you encounter an opening parenthesis) S.push (c); Finally add the new minus sign to the stack}} else if (' * ' ==c| | ' /' ==c| | '        (' ==c)//If it is a multiplication or an opening parenthesis, because they have a high priority, so go directly into the stack.        {S.push (c);        } else if (' \ n ' ==c)//Determine if all symbols have been converted to completion {break; } else//can go to this else, is the symbol I do not know {//printf ("\nerror:input error,the character%d Cann ' t recognize!\n"          , c);        return-1; } c=* (Infix+i);    Remove the next character for conversion i++;      } while (S.size ())//conversion completed, there may be no stack of operation symbols {e=s.top (); S.pop ();      Postfix[j++]=e;    Postfix[j++]= "; } return true; /* Computes the result parameter of the suffix expression: Arr uses a space-delimited suffix expression string. Example: arr= "5 +" resultSave results after calculation note: How to use the stack to calculate the result of the suffix expression: take out the suffix expression in order to compare the symbol, if it is a number, then directly into the stack, if it is a symbol, the stack two times, pop up two to calculate the factor, to calculate, and then the calculation results into the stack. Know that all the symbols in the suffix expression have been compared.  */double Calculate (char *arr) {//printf ("%s\n", arr); Double d,e,f; D,e Store two factors.  F Store the results of the d,e calculation.  Stack<double> s; Char *op; Holds each factor or operator in the suffix expression char *buf=arr;  Declaring BUFHE saveptr Two variables is required for the Strtok_r function.  Char *saveptr=null;      while ((Op=strtok (buf, ""))!=null)//Use the STRTOK_R function to separate the string {buf=null;            Switch (op[0]) {case ' + ': d=s.top (); S.pop ();          E=s.top (); S.pop ();          F=d+e;          S.push (f);        Break            Case '-': D=s.top (); S.pop ();          E=s.top (); S.pop ();          f=e-d;          S.push (f);        Break          Case ' * ': d=s.top (); S.pop ();          E=s.top (); S.pop ();          F=d*e;          S.push (f);        Break          Case '/': D=s.top (); S.pop ();          E=s.top (); S.pop ();          f=e/d;          S.push (f);        Break Default:d=atof (OP); is not an operator, KenIt's a factor.          So, with the Atof function, convert the string to a double type s.push (d);        Break  }} double Result=s.top (); S.pop (); return result;}




C + + suffix expression (inverse polish) for four expression value, using Stack in STL

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.