C++

Thursday, 11 October 2012

Stacks- Converting Infix Expression to Postfix Expression

Algorithm to Convert Infix Exp to Postfix Expression:
1. opstk = the empty stack;
2. while (not end of input){
3.   symb = next input character;
4.   if (symb is an operand)
        add symb to the postfix string
5.   else{
6.         while (!opstk.empty () && prcd(opstk.Top(), symb)){
7.       topsymb = opstk.pop();
8.            add topsymb to the postfix string;
          } /* end while*/
9.        opstk.push(symb);
     } /* end else*/
} /* end while*/
10. while (!opstk.empty()){
11. Topsymb = opstk.pop();
 12. add topsymb to the postfix string;
} /* end while*/

9. if (opstk.empty () || symb != ‘)’)
       opstk .push(symb);
    else
       topsymb = opstk.pop();
Precedence rules for parenthesis:
prcd(‘(’,op) = FALSE
Prcd(op,’(’) = FALSE
prcd(op,’)’) = TRUE
prcd(‘)’,op) = undefined

//Converting Infix expression to postfix expression
#include <iostream>
#include <process.h>
#include <string>
#include <math.h>
using namespace std;
bool prcd (char, char); //function declaration
template <class Type>
//stack class
class Stack
{
private:
          Type *stack;
          int top;
          int Maxsize;
public:
          Stack(int Max) //1-argument constructor
          {
                   stack = new Type[Max];
                   top = -1;
                   Maxsize = Max;
          }
//Boundary check, function to check weather stack is Empty or not.
          bool isempty()
          {
                   return (top==-1);
          }
//Boundary check, function to check weather stack is Full or not.
          bool isfull()
          {
                   if (top == Maxsize)
                             return true;
                   else
                             return false;
          }
//function to push value into stack
          void push(Type val)
          {
                   if (!isfull())
                   {
                             top++;
                             stack[top] = val;
                   }
                   else
                   {
                             cout << "stack overflow";
                             exit(1);
                   }
          }
//function to pop out value from stack
          Type pop()
          {
                   if (!isempty())
                   {
                             int x = stack[top];
                             top--;
                             return x;
                   }
                   else
                   {
                             cout << "stack underflow";
                             exit(1);
                   }
          }
//return top element of the stack
          Type stacktop()
          {
                   if (!isempty())
                             return stack[top];
                   else
                   {
                             cout << "stack underflow";
                             exit(1);
                   }

          }
};
//Main Function
void main()
{
          Stack<char> s(10);
          string exp, post ;
          cout << "Enter expression";
          cin >> exp;
          for (int i=0; i< exp.length(); i++)
          {
                   char symb= exp[i];
                   if (symb >='A' && symb <= 'Z') // if alphabet
                             post.append(1,symb); // append string
                   else
                   {
                             while (!s.isempty() && prcd(s.stacktop(), symb)) // function call
                             {
                                      char topsymb = s.pop();
                                      post.append(1,topsymb);
                             }
                             if (s.isempty() || symb != ')')
                                      s.push(symb);
                             else
                                      s.pop();
                   }
                  
          }
          while (!s.isempty())
          {
                   char topsymb = s.pop();
                   post.append(1,topsymb);
          }
                  
          cout << "Result is "<<  post;       
}
//Defination of the precedence checking function:
bool prcd (char top, char symb)
{
          if (top == '(' || symb  == '(')
                   return false;
          if (symb == ')')
                   return true;
          if (symb == '$')
                   return false;
          if (top == '$')
                   return true;
          if ((top== '*' ||top == '/') && ( symb== '*' || symb == '/'))
                   return true;
          if (symb == '+' ||symb == '-')
                   return true;
          else
                   return false;
}

Example Dry Run:


         

Wednesday, 10 October 2012

Parenthesis Stack:


Consider a mathematical expression that includes several sets of nested parenthesis.
7 – ((x * (( x + y) / (j - 3)) + Y) / (4 – 2))
In expression we want to check
  1. There are an equal number of right and left parenthesis.
  2.  Every right parenthesis is preceded by a matching left parenthesis.
Expressions like ((A+B) or A+B( violates condition 1 and expressions like )A + B(-C violate condition 2.
Nested Depth: is the number of scopes that have been opened and not yet closed.
Parenthesis count: no of left parenthesis – no of right parenthesis.

Expression id valid if following conditions are met.
  •  Parenthesis count at end should be zero.
  •  Parenthesis count at each point in expression should be non negative.
              7 – ( ( x *  ( (  x + y )  / ( j -  3  )  ) + Y )  / ( 4 – 2.5 ) )
              0 0 1 2 2 2 3 4 4 4 4 3 3 4 4 4 4 3 2 2  2 1 1 2 2 2  2 1 0
               ( ( A + B ) and (A + B] is illegal
         1  2 2 2 2 1

Algorithm for Example:


valid = true
s = empty stack;
while (we have not read the entire string) {
     read the next symbol (symb) in the string;
     if (symb == ‘(’ || symb == ‘{’ || symb == ‘[’ )
         s.push(symb);
   if (symb == ‘)’ || symb == ‘}’ || symb == ‘]’ )
         if (empty(s))
            valid = false;
         else{
               i = s.pop();
               if (i is not the matching opener of symb)
                 valid = false }
}// end of while
if (!s.empty()) valid = false;
if (valid)
   cout << “String is valid”;
else cout << “String is not valid”;

Dry Run for parenthesis stack: