Our Feeds

Thursday, 8 October 2015

AJITH KP

Infix to Prefix using Stack in C++

Hi GuyZ,
     This is just another sample program question which you have to solve in "Data Structures and Algorithms" paper.

Steps

1. Reverse the infix expression.
2. Convert '(' to ')' and ')' to '('.
3. Do a postfix conversion
4. Reverse the postfix expression to get infix expression.


Source Code

/*
    [][][]
    [][][]
    [][][]
    [][][]  TerminalCoders.Blogspot.Com
    [][][]
    [][][]
    [][][]
*/
 
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
class stack
{
 char arr[1024];
 int ptr;
 public:
 stack()
 {
  ptr = 0;
 }
 int isEmpty()
 {
  if(ptr==0)return 1;
  return 0;
 }
 char top()
 {
  return arr[ptr-1];
 }
 void push(char c)
 {
  arr[ptr++] = c;
 }
 char pop()
 {
  return arr[--ptr];
 }
};
int isOperator(char character)
{
    if (character == '+' || character == '-' || character == '*' || character == '/' || character=='^') {
        return 1;
    }    
    return 0;
}
int isOperand(char character)
{    
    if (isOperator(character) == 0 && character != '(' && character != ')') {
        return 1;
    }
    return 0;
}

int isp(char op) {
 switch(op)
 {
  case '+':
  case '-':
   return 1;
   break;
  case '*':
  case '/':
   return 3;
   break;
  case '^':
   return 6;
   break;
  return 0;
  break;
 }
}

int icp(char op) {
 switch(op)
 {
  case '+':
  case '-':
   return 2;
   break;
  case '*':
  case '/':
   return 4;
   break;
  case '^':
   return 5;
   break;
  return 0;
  break;
 }
}
void reverse(char* str, int len) 
{
 for(int i=0; i<len/2; i++) 
 {
  char temp=str[i];
  str[i]=str[len-i-1];
  str[len-i-1]=temp;
 }
}
int main()
{
 char inf[1024], pre[1024], tmp[1024], *ptr;
 stack s;
 cout<<"Infix: ";
 cin>>inf;
 reverse(inf, strlen(inf));
 strcpy(tmp, "");
 strcpy(pre, "");
 ptr = inf;
 while(*ptr!='\0')
 {
  if(isOperand(*ptr))
  {
   sprintf(tmp, "%c", *ptr);
   strcat(pre, tmp);
  }
  else if(isOperator(*ptr))
  {
   while(!s.isEmpty() && s.top()!=')' && isp(s.top())>icp(*ptr))
   {
    sprintf(tmp, "%c", s.pop());
    strcat(pre, tmp);
   }
   s.push(*ptr);
  }
  else if(*ptr==')')
  {
   s.push(*ptr);
  }
  else if(*ptr=='(')
  {
   while(!s.isEmpty())
   {
    if(s.top()==')')
    {
     s.pop();
     break;
    }
    if(s.top()=='(')
    {
     continue;
    }
    sprintf(tmp, "%c", s.pop());
    strcat(pre, tmp);
   }
  }
  *ptr++;
 }
 while(!s.isEmpty())
 {
  sprintf(tmp, "%c", s.top());
  strcat(pre, tmp);
  s.pop();
 }
 reverse(pre, strlen(pre));
 cout<<pre<<endl;
}