Inverse Polish formula and expression solving

Source: Internet
Author: User

Inverse Polish formula and expression solving

/************** Inverse Polish-suffix notation preprocessing-> infix to postfix algorithm: while (the expression is not empty) if (when an operand is encountered) directly outputs else if (when an operator op is encountered) op is (directly in the stack s op is) s. push the output until (op is an arithmetic operation, if (s is empty | s. top is (| op with a higher priority than s. top) op into the stack else s. push output if (! S. empty) s. push output computing algorithm: if (encountering operands) into Stack s else (encountering operator) s. push two elements for calculation and result into Stack *********************/# include
 
  
# Include
  
   
Using namespace std; typedef struct tagCalc {bool is_op; union {char op; int value ;};} Calc; int main () {stack
   
    
S; Calc calc; int ch; while (1) {while (ch = getchar () & ch! = '\ N') {if (NULL = strchr ("+-*/", ch) // operand {if (strchr ("()", ch) = NULL) printf ("% c", ch); if ('= ch) {calc. is_op = 1; calc. op = ch; s. push (calc);} else if (')' = ch) {while (! S. empty () {calc = s. top (); s. pop (); if ('= calc. op) break; printf ("% c", calc. op) ;}} else {if (s. empty () | s. top (). op = '(' | (NULL! = Strchr ("*/", ch) & NULL! = Strchr ("+-", s. top (). op) {calc. is_op = true; calc. op = ch; s. push (calc);} else {calc = s. top (); s. pop (); printf ("% c", calc. op) ;}}while (! S. empty () {calc = s. top (); s. pop (); printf ("% c", calc. op) ;}printf ("\ n ");}}
   
  
 

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.