Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 27th, 2012  |  syntax: None  |  size: 1.99 KB  |  hits: 27  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Using Stacks in C   to Evaluate the Postfix Expression
  2. int evaluatePostFix(string postfix_expression){
  3. //Create a new stack
  4. stack<int> theStack;
  5. //Loops while the postfix expression string still contains values
  6. while(postfix_expression.length()>=1){
  7.     //Loops on a number an whitespace
  8.     while(isdigit(postfix_expression.at(0)) || isspace(postfix_expression.at(0))){
  9.         //Holds a number that is above two digits to be added to the stack
  10.         string completeNum;
  11.         if(isdigit(postfix_expression.at(0))){
  12.             //Add the digit so it can become a full number if needed
  13.             completeNum+=postfix_expression.at(1);
  14.         }
  15.         else {
  16.             //Holds the integer version of completeNum
  17.             int intNum;
  18.             //Make completeNum an int
  19.             intNum=atoi(completeNum.c_str());
  20.             //push the number onto the stack
  21.             theStack.push(intNum);
  22.         }
  23.         //Check to see if it can be shortened
  24.         if(postfix_expression.length()>=1){
  25.             //Shorten the postfix expression
  26.             postfix_expression=postfix_expression.substr(1);
  27.         }
  28.     }
  29.     //An Operator has been found
  30.     while(isOperator(postfix_expression.at(0))){
  31.         int num1, num2;
  32.         char op;
  33.         //Grabs from the top of the stack
  34.         num1=theStack.top();
  35.         //Pops the value from the top of the stack - kinda stupid how it can return the value too
  36.         theStack.pop();
  37.         //Grabs the value from the top of the stack
  38.         num2=theStack.top();
  39.         //Pops the value from the top of the stack
  40.         theStack.pop();
  41.         //Grab the operation
  42.         op=postfix_expression.at(0);
  43.         //Shorten the postfix_expression
  44.         postfix_expression=postfix_expression.substr(1);
  45.         //Push result onto the stack
  46.         theStack.push(Calculate(num1,num2, op));
  47.     }
  48. }
  49. return theStack.top();
  50.        
  51. if(isdigit(postfix_expression.at(0))){
  52.     //Add the digit so it can become a full number if needed
  53.     completeNum+=postfix_expression.at(1);
  54. }