3. For given expression eg. a-b*c-d/e+f construct inorder sequence and traverse it using postorder traversal(non recursive).

#include<iostream>
#include<string>
#include<stack>
using namespace std;

int getweight(char c)
{
 switch(c)
 {
  case '^' :  return 3;
     break;
  case '*' : 
  case '/' :  return 2;
     break;
  case '+' :
  case '-' : return 1;
     break;
  default  : return 0;
 }
}


void infix2postfix(char infix[], char postfix[], int size ,int sizepos)
{
 stack <char> s;
 int i = 0;
 int j = 0;
 int weight = 0;
 char ch;
 while( i < size)  
 {
  ch = infix[i];
  //cout<<i<<endl;
 // cout<<ch<<endl;
  if ( ch == '(' )
  {
   s.push(ch);
   i++;
   continue;

  }
  else if( ch == ')')
  {
   if(s.top() == '(')
   {
    s.pop();
    
   }
   else
   {
    while(s.top() != '(')
    {
     postfix[j++] = s.top();
     s.pop();
    }
    s.pop();
    i++;
    continue;

   }
  }
  else
  {
   weight = getweight(ch);
   if(weight == 0)
   {
    postfix[j++] = ch;
   }
   else if(s.empty())
   {
    s.push(ch);
   }
   else if(getweight(s.top()) < weight)
   {
    s.push(ch);
   }
   else 
   {  
    if(getweight(s.top()) >= weight )
    {
     postfix[j++] = s.top();
     s.pop();
    }
    s.push(ch);
   }
  }
  i++;
 }
 while(!s.empty())
 {
  if(getweight(s.top())!= 0)
  { postfix[j++] = s.top();
   s.pop();
  }
 }
 for(int i = 0 ; i < sizepos ; i++)
  cout<<postfix[i];
} 
   
    
 
int main()
{
 char infix[25];
 cout<<"ENTER THE INFIX EXPRESSION \t=\t";
 cin>>infix;
 int size = 0,sizepos = 0;
 for( int i = 0 ; infix[i] != '\0' ; i++)
 {
  size++;
  if( infix[i] != '(' && infix[i] != ')')
   sizepos++;
 }
 cout<<"size:"<<size<<endl;
 char postfix[sizepos];
 infix2postfix(infix, postfix, size,sizepos);
 
 return 0;
}

Comments

Popular posts from this blog

2. Beginning with an empty binary search tree, Construct binary search tree by inserting the values in the order given. After constructing a binary tree -i.Insert new nodeii.Find number of nodes in longest path iii.Minimum data value found inthe tree iv.Change a tree so that the roles of the left and right pointers are swapped at every node v.Search a value

1. A book consists of chapters, chapters consist of sections and sections consist of subsections. Construct a tree and print the nodes. Find the time and space requirements of your method.

6. Implement all the functions of a dictionary (ADT) using hashing.Data: Set of (key, value) pairs, Keys are mapped to values, Keys must be comparable, Keys must be uniqueStandard Operations: Insert(key, value), Find(key), Delete(key)