Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
Last Updated :
19 Mar, 2022
Conversion of infix to postfix expression can be done elegantly using two precedence function. Each operator is assigned a value (larger value means higher precedence) which depends upon whether the operator is inside or outside the stack. Also the right and left associativity for different operators can be handled by varying it’s values in the two precedence functions.
Infix expression example: a+b*c
Its corresponding postfix expression: abc*+
Following steps explains how these conversion has done.
Step 1: a + bc* (Here we have two operators: + and * in which * has higher precedence and hence it will be evaluated first).
Step 2: abc*+ (Now we have one operator left which is + so it is evaluated)
To know more about infix and postfix expressions visit the links.
Note : In this article, we are assuming that all operators are left to right associative.
Examples:
Input: str = “a+b*c-(d/e+f*g*h)”
Output: abc*+de/fg*h*+-
Step 1: a+b*c-(de/+f*g*h)
Step 2: a+b*c-(de/+fg* *h)
Step 3: a+b*c-(de/+fg*h*)
Step 4: a+b*c-(de/fg*h*+)
Step 5: a+bc*-de/fg*h*+
Step 6: abc*+-de/fg*h*+
Step 7: abc*+de/fg*h*+-
Input: a+b*c/h
Output: abc*h/+
Step 1: a+bc*/h
Step 2: a+bc*h/
Step 3: abc*h/+
Approach:
- If the input character is an operand, print it.
- If the input character is an operator-
- If stack is empty push it to the stack.
- If its precedence value is greater than the precedence value of the character on top, push.
- If its precedence value is lower or equal then pop from stack and print while precedence of top char is more than the precedence value of the input character.
- If the input character is ‘)’, then pop and print until top is ‘(‘. (Pop ‘(‘ but don’t print it.)
- If stack becomes empty before encountering ‘(‘, then it’s a invalid expression.
- Repeat steps 1-4 until input expression is completely read.
- Pop the remaining elements from stack and print them.
The above method handles right associativity of exponentiation operator (here, ^) by assigning it higher precedence value outside stack and lower precedence value inside stack whereas it’s opposite for left associative operators.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int isOperator( char input)
{
switch (input) {
case '+' :
return 1;
case '-' :
return 1;
case '*' :
return 1;
case '%' :
return 1;
case '/' :
return 1;
case '(' :
return 1;
}
return 0;
}
int isOperand( char input)
{
if (input >= 65 && input <= 90
|| input >= 97 && input <= 122)
return 1;
return 0;
}
int inPrec( char input)
{
switch (input) {
case '+' :
case '-' :
return 2;
case '*' :
case '%' :
case '/' :
return 4;
case '(' :
return 0;
}
}
int outPrec( char input)
{
switch (input) {
case '+' :
case '-' :
return 1;
case '*' :
case '%' :
case '/' :
return 3;
case '(' :
return 100;
}
}
void inToPost( char * input)
{
stack< char > s;
int i = 0;
while (input[i] != '\0' ) {
if (isOperand(input[i])) {
printf ( "%c" , input[i]);
}
else if (isOperator(input[i])) {
if (s.empty()
|| outPrec(input[i]) > inPrec(s.top()))
s.push(input[i]);
else {
while (!s.empty()
&& outPrec(input[i]) < inPrec(s.top())) {
printf ( "%c" , s.top());
s.pop();
}
s.push(input[i]);
}
}
else if (input[i] == ')' ) {
while (s.top() != '(' ) {
printf ( "%c" , s.top());
s.pop();
if (s.empty()) {
printf ( "Wrong input\n" );
exit (1);
}
}
s.pop();
}
i++;
}
while (!s.empty()) {
if (s.top() == '(' ) {
printf ( "\n Wrong input\n" );
exit (1);
}
printf ( "%c" , s.top());
s.pop();
}
}
int main()
{
char input[] = "a+b*c-(d/e+f*g*h)" ;
inToPost(input);
return 0;
}
|
Java
import static java.lang.System.exit;
import java.util.Stack;
class GFG {
static int isOperator( char input)
{
switch (input) {
case '+' :
return 1 ;
case '-' :
return 1 ;
case '*' :
return 1 ;
case '%' :
return 1 ;
case '/' :
return 1 ;
case '(' :
return 1 ;
}
return 0 ;
}
static int isOperand( char input)
{
if (input >= 65 && input <= 90
|| input >= 97 && input <= 122 ) {
return 1 ;
}
return 0 ;
}
static int inPrec( char input)
{
switch (input) {
case '+' :
case '-' :
return 2 ;
case '*' :
case '%' :
case '/' :
return 4 ;
case '(' :
return 0 ;
}
return 0 ;
}
static int outPrec( char input)
{
switch (input) {
case '+' :
case '-' :
return 1 ;
case '*' :
case '%' :
case '/' :
return 3 ;
case '(' :
return 100 ;
}
return 0 ;
}
static void inToPost( char [] input)
{
Stack<Character> s = new Stack<Character>();
int i = 0 ;
while (input.length != i) {
if (isOperand(input[i]) == 1 ) {
System.out.printf( "%c" , input[i]);
}
else if (isOperator(input[i]) == 1 ) {
if (s.empty()
|| outPrec(input[i]) > inPrec(s.peek())) {
s.push(input[i]);
}
else {
while (!s.empty()
&& outPrec(input[i]) < inPrec(s.peek())) {
System.out.printf( "%c" , s.peek());
s.pop();
}
s.push(input[i]);
}
}
else if (input[i] == ')' ) {
while (s.peek() != '(' ) {
System.out.printf( "%c" , s.peek());
s.pop();
if (s.empty()) {
System.out.printf( "Wrong input\n" );
exit( 1 );
}
}
s.pop();
}
i++;
}
while (!s.empty()) {
if (s.peek() == '(' ) {
System.out.printf( "\n Wrong input\n" );
exit( 1 );
}
System.out.printf( "%c" , s.peek());
s.pop();
}
}
static public void main(String[] args)
{
char input[] = "a+b*c-(d/e+f*g*h)" .toCharArray();
inToPost(input);
}
}
|
Python3
def isOperator( input ):
switch = {
'+' : 1 ,
'-' : 1 ,
'*' : 1 ,
'/' : 1 ,
'%' : 1 ,
'(' : 1 ,
}
return switch.get( input , False )
def isOperand( input ):
if (( ord ( input ) > = 65 and ord ( input ) < = 90 ) or
( ord ( input ) > = 97 and ord ( input ) < = 122 )):
return 1
return 0
def inPrec( input ):
switch = {
'+' : 2 ,
'-' : 2 ,
'*' : 4 ,
'/' : 4 ,
'%' : 4 ,
'(' : 0 ,
}
return switch.get( input , 0 )
def outPrec( input ):
switch = {
'+' : 1 ,
'-' : 1 ,
'*' : 3 ,
'/' : 3 ,
'%' : 3 ,
'(' : 100 ,
}
return switch.get( input , 0 )
def inToPost( input ):
i = 0
s = []
while ( len ( input ) ! = i):
if (isOperand( input [i]) = = 1 ):
print ( input [i], end = "")
elif (isOperator( input [i]) = = 1 ):
if ( len (s) = = 0 or
outPrec( input [i]) >
inPrec(s[ - 1 ])):
s.append( input [i])
else :
while ( len (s) > 0 and
outPrec( input [i]) <
inPrec(s[ - 1 ])):
print (s[ - 1 ], end = "")
s.pop()
s.append( input [i])
elif ( input [i] = = ')' ):
while (s[ - 1 ] ! = '(' ):
print (s[ - 1 ], end = "")
s.pop()
if ( len (s) = = 0 ):
print ( 'Wrong input' )
exit( 1 )
s.pop()
i + = 1
while ( len (s) > 0 ):
if (s[ - 1 ] = = '(' ):
print ( 'Wrong input' )
exit( 1 )
print (s[ - 1 ], end = "")
s.pop()
input = "a+b*c-(d/e+f*g*h)"
inToPost( input )
|
C#
using System.Collections.Generic;
using System;
public class GFG {
static int isOperator( char input)
{
switch (input) {
case '+' :
return 1;
case '-' :
return 1;
case '*' :
return 1;
case '%' :
return 1;
case '/' :
return 1;
case '(' :
return 1;
}
return 0;
}
static int isOperand( char input)
{
if (input >= 65 && input <= 90
|| input >= 97 && input <= 122) {
return 1;
}
return 0;
}
static int inPrec( char input)
{
switch (input) {
case '+' :
case '-' :
return 2;
case '*' :
case '%' :
case '/' :
return 4;
case '(' :
return 0;
}
return 0;
}
static int outPrec( char input)
{
switch (input) {
case '+' :
case '-' :
return 1;
case '*' :
case '%' :
case '/' :
return 3;
case '(' :
return 100;
}
return 0;
}
static void inToPost( char [] input)
{
Stack< char > s = new Stack< char >();
int i = 0;
while (input.Length != i) {
if (isOperand(input[i]) == 1) {
Console.Write(input[i]);
}
else if (isOperator(input[i]) == 1) {
if (s.Count == 0
|| outPrec(input[i]) > inPrec(s.Peek())) {
s.Push(input[i]);
}
else {
while (s.Count != 0
&& outPrec(input[i]) < inPrec(s.Peek())) {
Console.Write(s.Peek());
s.Pop();
}
s.Push(input[i]);
}
}
else if (input[i] == ')' ) {
while (s.Peek() != '(' ) {
Console.Write(s.Peek());
s.Pop();
if (s.Count == 0) {
Console.Write( "Wrong input\n" );
return ;
}
}
s.Pop();
}
i++;
}
while (s.Count != 0) {
if (s.Peek() == '(' ) {
Console.Write( "\n Wrong input\n" );
return ;
}
Console.Write(s.Peek());
s.Pop();
}
}
static public void Main()
{
char [] input = "a+b*c-(d/e+f*g*h)" .ToCharArray();
inToPost(input);
}
}
|
Javascript
<script>
function isOperator(input)
{
switch (input) {
case '+' :
return 1;
case '-' :
return 1;
case '*' :
return 1;
case '%' :
return 1;
case '/' :
return 1;
case '(' :
return 1;
}
return 0;
}
function isOperand(input)
{
if (input.charCodeAt() >= 65 && input.charCodeAt() <= 90
|| input.charCodeAt() >= 97 && input.charCodeAt() <= 122) {
return 1;
}
return 0;
}
function inPrec(input)
{
switch (input) {
case '+' :
case '-' :
return 2;
case '*' :
case '%' :
case '/' :
return 4;
case '(' :
return 0;
}
return 0;
}
function outPrec(input)
{
switch (input) {
case '+' :
case '-' :
return 1;
case '*' :
case '%' :
case '/' :
return 3;
case '(' :
return 100;
}
return 0;
}
function inToPost(input)
{
let s = [];
let i = 0;
while (input.length != i) {
if (isOperand(input[i]) == 1) {
document.write(input[i]);
}
else if (isOperator(input[i]) == 1) {
if (s.length == 0
|| outPrec(input[i]) > inPrec(s[s.length - 1])) {
s.push(input[i]);
}
else {
while (s.length != 0
&& outPrec(input[i]) < inPrec(s[s.length - 1])) {
document.write(s[s.length - 1]);
s.pop();
}
s.push(input[i]);
}
}
else if (input[i] == ')' ) {
while (s[s.length - 1] != '(' ) {
document.write(s[s.length - 1]);
s.pop();
if (s.length == 0) {
document.write( "Wrong input" + "</br>" );
return ;
}
}
s.pop();
}
i++;
}
while (s.length != 0) {
if (s[s.length - 1] == '(' ) {
document.write( "</br>" + " Wrong input" + "</br>" );
return ;
}
document.write(s[s.length - 1]);
s.pop();
}
}
let input = "a+b*c-(d/e+f*g*h)" .split( '' );
inToPost(input);
</script>
|
How to handle operators with right to left associativity?
For example, power operator ^. The postfix of “a^b^c” would be “abc^^”, but the above solution would print postfix as “ab^c^” which is wrong.
In the above implementation, when we see an operator with equal precedence, we treat it same as lower. We need to consider the same if the two operators have left to associativity. But in case of right to left associativity, we need to treat it as higher precedence and push it to the stack.
Approach:
- If the input character is an operand, print it.
- If the input character is an operator-
- If stack is empty push it to the stack.
- If ((its precedence value is greater than the precedence value of the character on top) OR (precedence is same AND associativity is right to left)), push.
- If ((its precedence value is lower) OR (precedence is same AND associativity is left to right)), then pop from stack and print while precedence of top char is more than the precedence value of the input character.
- If the input character is ‘)’, then pop and print until top is ‘(‘. (Pop ‘(‘ but don’t print it.)
- If stack becomes empty before encountering ‘(‘, then it’s a invalid expression.
- Repeat steps 1-4 until input expression is completely read.
- Pop the remaining elements from stack and print them.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...