Stack | Set 2 (Infix to Postfix)

2.7

Prerequisite – Stack | Set 1 (Introduction)
Infix expression:The expression of the form a op b. When an operator is in-between every pair of operands.

Postfix expression:The expression of the form a b op. When an operator is followed for every pair of operands.

Why postfix representation of the expression?
The compiler scans the expression either from left to right or from right to left.

Consider the below expression: a op1 b op2 c op3 d
If op1 = +, op2 = *, op3 = +

The compiler first scans the expression to evaluate the expression b * c, then again scan the expression to add a to it. The result is then added to d after another scan.

The repeated scanning makes it very in-efficient. It is better to convert the expression to postfix(or prefix) form before evaluation.

The corresponding expression in postfix form is: abc*+d+. The postfix expressions can be evaluated easily using a stack. We will cover postfix expression evaluation in a separate post.

Algorithm
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output it.
3. Else,
…..3.1 If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the stack is empty), push it.
…..3.2 Else, Pop the operator from the stack until the precedence of the scanned operator is less-equal to the precedence of the operator residing on the top of the stack. Push the scanned operator to the stack.
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop and output from the stack until an ‘(‘ is encountered.
6. Repeat steps 2-6 until infix expression is scanned.
7. Pop and output from the stack until it is not empty.

Following is C implementation of the above algorithm

C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// Stack type
struct Stack
{
	int top;
	unsigned capacity;
	int* array;
};

// Stack Operations
struct Stack* createStack( unsigned capacity )
{
	struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));

	if (!stack) 
		return NULL;

	stack->top = -1;
	stack->capacity = capacity;

	stack->array = (int*) malloc(stack->capacity * sizeof(int));

	if (!stack->array)
		return NULL;
	return stack;
}
int isEmpty(struct Stack* stack)
{
	return stack->top == -1 ;
}
char peek(struct Stack* stack)
{
	return stack->array[stack->top];
}
char pop(struct Stack* stack)
{
	if (!isEmpty(stack))
		return stack->array[stack->top--] ;
	return '$';
}
void push(struct Stack* stack, char op)
{
	stack->array[++stack->top] = op;
}


// A utility function to check if the given character is operand
int isOperand(char ch)
{
	return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}

// A utility function to return precedence of a given operator
// Higher returned value means higher precedence
int Prec(char ch)
{
	switch (ch)
	{
	case '+':
	case '-':
		return 1;

	case '*':
	case '/':
		return 2;

	case '^':
		return 3;
	}
	return -1;
}


// The main function that converts given infix expression
// to postfix expression. 
int infixToPostfix(char* exp)
{
	int i, k;

	// Create a stack of capacity equal to expression size 
	struct Stack* stack = createStack(strlen(exp));
	if(!stack) // See if stack was created successfully 
		return -1 ;

	for (i = 0, k = -1; exp[i]; ++i)
	{
		// If the scanned character is an operand, add it to output.
		if (isOperand(exp[i]))
			exp[++k] = exp[i];
		
		// If the scanned character is an ‘(‘, push it to the stack.
		else if (exp[i] == '(')
			push(stack, exp[i]);
		
		// If the scanned character is an ‘)’, pop and output from the stack 
		// until an ‘(‘ is encountered.
		else if (exp[i] == ')')
		{
			while (!isEmpty(stack) && peek(stack) != '(')
				exp[++k] = pop(stack);
			if (!isEmpty(stack) && peek(stack) != '(')
				return -1; // invalid expression			 
			else
				pop(stack);
		}
		else // an operator is encountered
		{
			while (!isEmpty(stack) && Prec(exp[i]) <= Prec(peek(stack)))
				exp[++k] = pop(stack);
			push(stack, exp[i]);
		}

	}

	// pop all the operators from the stack
	while (!isEmpty(stack))
		exp[++k] = pop(stack );

	exp[++k] = '\0';
	printf( "%sn", exp );
}

// Driver program to test above functions
int main()
{
	char exp[] = "a+b*(c^d-e)^(f+g*h)-i";
	infixToPostfix(exp);
	return 0;
}

C++

/* C++ implementation to convert infix expression to postfix*/
// Note that here we use std::stack  for Stack operations
#include<bits/stdc++.h>
using namespace std;

//Function to return precedence of operators
int prec(char c)
{
    if(c == '^')
    return 3;
    else if(c == '*' || c == '/')
    return 2;
    else if(c == '+' || c == '-')
    return 1;
    else
    return -1;
}

// The main function to convert infix expression
//to postfix expression
void infixToPostfix(string s)
{
    std::stack<char> st;
    st.push('N');
    int l = s.length();
    string ns;
    for(int i = 0; i < l; i++)
    {
        // If the scanned character is an operand, add it to output string.
        if((s[i] >= 'a' && s[i] <= 'z')||(s[i] >= 'A' && s[i] <= 'Z'))
        ns+=s[i];

        // If the scanned character is an ‘(‘, push it to the stack.
        else if(s[i] == '(')
        
        st.push('(');
        
        // If the scanned character is an ‘)’, pop and to output string from the stack
        // until an ‘(‘ is encountered.
        else if(s[i] == ')')
        {
            while(st.top() != 'N' && st.top() != '(')
            {
                char c = st.top();
                st.pop();
               ns += c;
            }
            if(st.top() == '(')
            {
                char c = st.top();
                st.pop();
            }
        }
        
        //If an operator is scanned
        else{
            while(st.top() != 'N' && prec(s[i]) <= prec(st.top()))
            {
                char c = st.top();
                st.pop();
                ns += c;
            }
            st.push(s[i]);
        }

    }
    //Pop all the remaining elements from the stack
    while(st.top() != 'N')
    {
        char c = st.top();
        st.pop();
        ns += c;
    }
    
    cout << ns << endl;

}

//Driver program to test above functions
int main()
{
    string exp = "a+b*(c^d-e)^(f+g*h)-i";
    infixToPostfix(exp);
    return 0;
}
// This code is contributed by Gautam Singh

Java

/* Java implementation to convert infix expression to postfix*/
// Note that here we use Stack class for Stack operations

import java.util.Stack;

class Test
{
	// A utility function to return precedence of a given operator
	// Higher returned value means higher precedence
	static int Prec(char ch)
	{
	    switch (ch)
	    {
	    case '+':
	    case '-':
	        return 1;
	 
	    case '*':
	    case '/':
	        return 2;
	 
	    case '^':
	        return 3;
	    }
	    return -1;
	}
     
	// The main method that converts given infix expression
	// to postfix expression. 
	static String infixToPostfix(String exp)
	{
		// initializing empty String for result
		String result = new String("");
		
		// initializing empty stack
		Stack<Character> stack = new Stack<>();
		
	    for (int i = 0; i<exp.length(); ++i)
	    {
	    	char c = exp.charAt(i);
	    	
	         // If the scanned character is an operand, add it to output.
	        if (Character.isLetterOrDigit(c))
	            result += c;
	         
	        // If the scanned character is an '(', push it to the stack.
	        else if (c == '(')
	            stack.push(c);
	        
	        //  If the scanned character is an ')', pop and output from the stack 
	        // until an '(' is encountered.
	        else if (c == ')')
	        {
	            while (!stack.isEmpty() && stack.peek() != '(')
	                result += stack.pop();
	            
	            if (!stack.isEmpty() && stack.peek() != '(')
	                return "Invalid Expression"; // invalid expression                
	            else
	                stack.pop();
	        }
	        else // an operator is encountered
	        {
	            while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek()))
	            	result += stack.pop();
	            stack.push(c);
	        }
	 
	    }
	 
	    // pop all the operators from the stack
	    while (!stack.isEmpty())
	    	result += stack.pop();
	 
	    return result;
	}
  
    // Driver method 
    public static void main(String[] args) 
    {
    	String exp = "a+b*(c^d-e)^(f+g*h)-i";
        System.out.println(infixToPostfix(exp));
    }
}

Python


# Python program to convert infix expression to postfix

# Class to convert the expression
class Conversion:
    
    # Constructor to initialize the class variables
    def __init__(self, capacity):
        self.top = -1 
        self.capacity = capacity
        # This array is used a stack 
        self.array = []
        # Precedence setting
        self.output = []
        self.precedence = {'+':1, '-':1, '*':2, '/':2, '^':3}
    
    # check if the stack is empty
    def isEmpty(self):
        return True if self.top == -1 else False
    
    # Return the value of the top of the stack
    def peek(self):
        return self.array[-1]
    
    # Pop the element from the stack
    def pop(self):
        if not self.isEmpty():
            self.top -= 1
            return self.array.pop()
        else:
            return "$"
    
    # Push the element to the stack
    def push(self, op):
        self.top += 1
        self.array.append(op) 

    # A utility function to check is the given character
    # is operand 
    def isOperand(self, ch):
        return ch.isalpha()

    # Check if the precedence of operator is strictly
    # less than top of stack or not
    def notGreater(self, i):
        try:
            a = self.precedence[i]
            b = self.precedence[self.peek()]
            return True if a  <= b else False
        except KeyError: 
            return False
            
    # The main function that converts given infix expression
    # to postfix expression
    def infixToPostfix(self, exp):
        
        # Iterate over the expression for conversion
        for i in exp:
            # If the character is an operand, 
            # add it to output
            if self.isOperand(i):
                self.output.append(i)
            
            # If the character is an '(', push it to stack
            elif i  == '(':
                self.push(i)

            # If the scanned character is an ')', pop and 
            # output from the stack until and '(' is found
            elif i == ')':
                while( (not self.isEmpty()) and self.peek() != '('):
                    a = self.pop()
                    self.output.append(a)
                if (not self.isEmpty() and self.peek() != '('):
                    return -1
                else:
                    self.pop()

            # An operator is encountered
            else:
                while(not self.isEmpty() and self.notGreater(i)):
                    self.output.append(self.pop())
                self.push(i)

        # pop all the operator from the stack
        while not self.isEmpty():
            self.output.append(self.pop())

        print "".join(self.output)

# Driver program to test above function
exp = "a+b*(c^d-e)^(f+g*h)-i"
obj = Conversion(len(exp))
obj.infixToPostfix(exp)

# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

Output:

abcd^e-fgh*+^*+i-

 

 

Quiz: Stack Questions

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



2.7 Average Difficulty : 2.7/5.0
Based on 77 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.