Typical examples of problems stack - postfix notation (reverse Polish notation) is calculated

// compiler general use postfix notation solving the value of the expression ( RPN or reverse Polish notation )
// postfix expression is the process of calculating: scanning, if the item is an operand, push ; if it is operator, from exit two stack operands (the first exit right operation
// number ), for calculation, and the calculation result back onto the stack , after scanning the stack is stored in the calculation result .
// where noted: whether to support more than two operands of !
// between operand is certainly a delimiter;
// example: + 12 34 56 *
@ * 123456 + if, whether human or computer, are not done;

. 1 #include <the iostream>
 2 #include <Stack>
 . 3 #include <stdlib.h> // atoi () function
 . 4  the using  namespace STD;
 . 5  int main () { // can be calculated 99 operand, and the respective input item delimiter must EG:. 1 + 2. 4. 3 - * # 
. 6      char S [ 100 ]; // number of operations or operator 
. 7      stack < int > Z; // operand stack 
. 8      int A, B; // operation number 
. 9      the while (CIN && S >> S [ 0 ]! = ' # ' ) {
 10  //     the while (CIN S >> S &&!="#"){// can not figure out why! ! ! 
. 11          IF (S [ 0 ] == ' + ' ) { // addition, s [0] is used wonderful! The same can not use == s "+", think about why! ! ! 
12 is              B = z.top ();   
 13 is              z.pop ();
 14              A = z.top ();
 15              z.pop ();
 16              z.push (A + B);
 . 17          }
 18 is          the else  IF (S [ 0 ] == ' - ' ) { // subtraction 
. 19              B = z.top ();
 20 is             z.pop();
21             a=z.top();
22             z.pop();
23             z.push(a-b);             
24         }
25         else if(s[0]=='*'){//乘法
26             b=z.top(); 
27             z.pop();
28             a=z.top();
29             z.pop(); 
30             z.push(a*b);
31         }
32         else if(s[0] == ' / ' ) { // divider 
33 is             B = z.top ();
 34 is             z.pop ();
 35             A = z.top ();
 36             z.pop (); 
 37 [             z.push (A / B);
 38 is          } 
 39          the else z.push (atoi (S)); // operand 
40      }
 41 is      COUT << z.top (); // after scanning is stored in the stack calculation result
 42 is      return  0 ;
 43 is }

 

Guess you like

Origin www.cnblogs.com/TYXmax/p/10987940.html