Friday, 12 August 2016

Infix to Prefix conversion

/*
Write  a Program to convert infix to prefix string

Input String can have operators -> '+','-','%','/','*','^'
Precedence for + and - operator is same
Precedence for %,/,*,^ is same but higher than + and - operator

Algorithm 
1) Reverse the infix string ;
2) Replace '(' with ')' and ')' with '('
3) Use post fix algorithm as mentioned in previous post
4) Reverse the output string and print

Example 

Infix                 Prefix
(a+b*c)*d         *+a*bcd
(a+b*c)            +a*bc

 */
package prefix_conversion;

import java.util.Scanner;

/**
 *
 * @author shashank
 */

class stack
{
    char arr[];
    int top = -1;
    public stack(String s)
    {
        arr = new char[s.length()];
    }
    public boolean isempty()
    {
        return top==-1?true:false;
    }
    public void push(char c)
    {
     
        arr[++top] = c;
     
    }
    public char pop()
    {
     
        return arr[top--];
    }
    public char peek()
    {
        return arr[top];
    }
}

public class Prefix_conversion {

    public static int check_prec(char c)
    {
        if(c=='+'||c=='-')
            return 1;
        else if(c=='*'||c=='/'||c=='%'||c=='^')
            return 2;
        return 0;
         
    }
 
    public static void main(String[] args) {
     
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the infix string");
        String s = sc.next();
        stack st = new stack(s);
        String sb = "" ;
        char symbol;
     
        for(int i=s.length()-1;i>=0;i--)
        {
            symbol = s.charAt(i);
            if(Character.isLetter(symbol))
                sb = sb + symbol;
           else if(symbol==')')
           {
                st.push(symbol);
           }
            else if(symbol=='(')
            {
                while(st.peek()!=')')
                {
                    sb =   sb + st.pop();
                }
                st.pop();
             
            }
            else
            {
                if(!st.isempty() && !(st.peek()==')') && check_prec(symbol)<=check_prec(st.peek()))
                {
                  sb =  sb + st.pop();
                }
                st.push(symbol);
            }
        }
        while(!st.isempty())
        {
            sb =  sb + st.pop();
        }
        String t = "";
        for(int i=sb.length()-1;i>=0;i--)
        {
         t = t + sb.charAt(i);
     
        }
        System.out.print("prefix string is  -->" + t);
    }
 
}

No comments:

Post a Comment