Friday, 6 March 2020

Infix to Postfix Conversion in java

Step 1: Start
Step 2: Read the infix expression
Step 3: Scan every character of infix expression,
IF scanned character is
3.1 ( , then  push it on the stack
3.2 operand (whether a digit or a character) , add it to postfix expression
3.3  ) , then
a. Repeatedly pop from stack and add it to the postfix expression until  ( .
b. Discard the ( . That is, remove the ( from stack and do not add it to the postfix
3.4 operator, then
a. Repeatedly pop from stack and add each operator (popped from the stack) to the postfix expression which has the same precedence or a higher precedence
b. Push the operator to the stack

Step 4: Repeatedly pop from the stack and add it to the postfix expression until the stack is empty
Step 5: Stop


import java.util.Scanner;

class SNode
{
    char data;
    SNode next;
}
class Stack
{
    SNode top=null;
   public void push(char val)
    {
        SNode newnode = new SNode();
        newnode.data=val;
        if(top == null)
            top=newnode;
        else
        {
            newnode.next=top;
            top=newnode;
        }   
    }
    public char pop()
    {
            char temp=top.data;
            top=top.next;
            return temp;
    }
}

public class PostfixConversionDemo
{
    public static int getPriority(char ch)
    {
        if(ch == '*' || ch == '/' || ch == '%')
                return 2;
        if(ch == '-' || ch == '+')
            return 1;
        return 0;
    }
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        Stack ob = new Stack();
        System.out.println("Enter infix experession");
        StringBuffer infix=new StringBuffer(sc.next());
        StringBuffer postfix=new StringBuffer();
        char temp;
        for(int i=0;i<infix.length();i++)
        {
            char ch=infix.charAt(i);
            if(ch == '(')
                ob.push(ch);
            else if(ch == ')')
            {
                while( ob.top.data != '(')
                {
                     postfix.append(ob.pop());
                }
           
                ob.pop();
            }
            else if(ch == '*' ||ch == '/' ||ch == '+' ||ch == '-'|| ch == '%' )
            {
                while(ob.top != null && getPriority(ob.top.data) >=  getPriority(ch))
                {
                    postfix.append(ob.pop());                   
                }
                ob.push(ch);
            }
            else
                postfix.append(ch);
        }
        while(ob.top != null)
            postfix.append(ob.pop());
        System.out.println(postfix);
    }
}

No comments:

Post a Comment