Calculate the Infix Expression with Stack

Source: Internet
Author: User

This article summarizes the use of stacks (stack) to convert infix expressions (postfix expression) to postfix expressions (infix expression) and to calculate the results.

1 //calculation of string numbers (based on infix-to-suffix). cpp: The entry point that defines the console application. 2 //3 4#include"stdafx.h"5#include <string>6#include <stack>7#include <cctype>8#include <iostream>9 Ten //computes a suffix expression. (int type) One intPostfixexp (ConstSTD::string&exp) A { -std::stack<int>Numsta; -      for(inti =0; I! = Exp.size (); i++) the     { -         //to press a number in an expression into the stack -STD::stringnum; -          while(IsDigit (Exp[i])) +         { - Num.push_back (Exp[i]); +i++; A         } at  -         if(!num.empty ()) Numsta.push (Atoi (Num.c_str () )); -  -         //Encounter spaces continue iteration -         if(Exp[i] = =' ')Continue; -          in         //An operator pops up the top two elements of the stack and presses the result into the stack -         if(Exp[i] = ='+'|| Exp[i] = ='-'|| Exp[i] = ='*'|| Exp[i] = ='/') to         { +             intNUM1; -             intnum2; the             if(!numsta.empty ()) *             { $NUM1 =numsta.top ();Panax Notoginseng Numsta.pop (); -             } the             if(!numsta.empty ()) +             { Anum2 =numsta.top (); the Numsta.pop (); +             } -             //Calculation $             Switch(Exp[i]) $             { -              Case '+': Numsta.push (NUM1 +num2); -                  Break; the              Case '-': Numsta.push (NUM1-num2); -                  Break;Wuyi              Case '*': Numsta.push (NUM1 *num2); the                  Break; -              Case '/': Numsta.push (NUM1/num2); Wu                  Break; -             default: About                  Break; $             } -         } -  -     } A     returnnumsta.top (); + } the  - //infix suffix e.g. 2 + 3 * 5 + (7 * 8 + 9) * 2 3 5 * + 7 8 * 9 + * + $STD::stringPostfixtoinfix (ConstSTD::string&exp) the { theSTD::stringresult; thestd::stack<Char>operators; the      for(inti =0; I < exp.size (); i++) -     { in          while(IsDigit (Exp[i])) the         { the Result.push_back (Exp[i]); Abouti++; the         } the         //If the end number is non-single digit, the array index will be out of bounds, because string is not a true character array, the result is not affected by the cross-border the         //if (i >= exp.size ()) break; +         //Add a space separator -Result.push_back (' '); the         //Encounter spaces continue iterationBayi         if(Exp[i] = =' ')Continue; the         //when the operator is encountered, check the top element of the stack priority, if it is a high priority/equal priority operator, pop up the stack operator, after completion of the expression of the operator press into the         if(Exp[i] = ='+'|| Exp[i] = ='-') -         { -              while(!operators.empty () && operators.top ()! ='(') the             { the                 //when the top element of the stack is +-*/, (the lowest priority in the stack, the highest precedence in an expression ) the Result.push_back (Operators.top ()); the Operators.pop (); -Result.push_back (' '); the             } the Operators.push (Exp[i]); the         }94         Else if(Exp[i] = ='*'|| Exp[i] = ='/') the         { the              while(!operators.empty () && (operators.top () = ='*'|| Operators.top () = ='/')) the             {98                 //if (operators.top () = = ' * ' | | operators.top () = = '/') About Result.push_back (Operators.top ()); - Operators.pop ();101Result.push_back (' ');102             }103 Operators.push (Exp[i]);104         } the         Else if(Exp[i] = ='(') Operators.push ('(');106         Else if(Exp[i] = =')')107         {108              while(Operators.top ()! ='(')109             { the Result.push_back (Operators.top ());111 Operators.pop (); theResult.push_back (' ');113             } the             //Eject ( the Operators.pop (); the         }117         118     }119      while(!operators.empty ()) -     {121 Result.push_back (Operators.top ());122Result.push_back (' ');123 Operators.pop ();124     } the     126     returnresult;127 } - 129 intMain () the {131Std::cout << Postfixexp (Postfixtoinfix ("2 + 3 * 5 + (7 * 8 + 9) *")) <<Std::endl; theSystem"Pause");133     return 0;134}

Calculate the Infix Expression with Stack

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.