Skip to main content

Infix, prefix and postfix notations

Mathematical expressions can be written in 3 different methods - infix, postfix and prefix.

Infix notation

All these days we have been using infix notation. In this operators are written between the operands. Some operators are having higher priorities than others. If some expressions are enclosed in brackets, then they are evaluated first.

e.g.
    (A+B)*C
Here + operator will operate on A and B as it is between them. Though * has higher priority, as A+B is enclosed in brackets, that is evaluated before multiplication.

Postfix notation

In a postfix notation - also called Reverse Polish Notation, operator is written after the operands. The operator operates on two operands to its immediate left. And expressions are always evaluated from left to right. Brackets do not have any effect on this.

e.g.
(A+B)*C in postfix is  AB+C*
A+B*C+D in postfix is ABC*+D+

Prefix notation

In a prefix notation, operator is written before the operands. And just like postfix, expressions are evaluated from left to right and brackets do not have any effect.

e.g.
(A+B)*C is prefix is   *+ABC
A+B*C+D in prefix is   ++A*BCD

Postfix notation is quite useful in processing of expression as it can be evaluated in single parsing.

Next let us consider how to convert from one notation to another.

Conversion of an infix expression to postfix expression

In order to convert an infix expression to postfix, we need to use an operator stack.

While traversing all the operands are transferred to output expression. When  an operator is encountered it is pushed to stack. But if the stack already has higher or equal priority operators, these are popped out and added to output expression. If there is a bracket - opening bracket, that too is pushed to stack. But when there is a closing bracket, then all the operators in the stack up to opening brackets are to be popped out of stack and added to output expression. In the end, if the stack has any more operators, they are popped and added to output expression.

Here is the algorithm

  •  Create an empty stack called opstack for keeping operators. Create an empty array for output.
  • Scan the token list from left to right.
    • If the token is an operand, append it to the end of the output string.
    • If the token is a left parenthesis, push it on the opstack.
    • If the token is a right parenthesis, pop the opstack until the corresponding left parenthesis is removed. Append each operator to the end of the output string.
    • If the token is an operator, *, /, +, or -, push it on the opstack. However, first remove any operators already on the opstack that have higher or equal precedence and append them to the output string.
  •  When the input expression has been completely processed, check the operator stack. Any operators still on the stack can be removed and appended to the end of the output string.
Here is the function for conversion.

int is_operator(char ch)
{
switch(ch)
{
case '+':
case '-':
case '/':
case '*':
case '%':
case '^':
return 1;
default : return 0;
}
}
int priority(char ch)
{
switch(ch)
{
case '+':
case '-':return 1;
case '/':
case '*':
case '%':return 2;
case '^':return 3;

default : return 0;
}
}

void convert(char *input, char *output)
{
struct stack s1;
s1.top = -1;
while(*input)
{
char ch = *input++;
char ch2;
if(ch=='(')
push(&s1,ch);
else if(ch==')')
{
while(!is_empty(&s1) && ( (ch=pop(&s1))!='('))
*output++ = ch;
}
else if(is_operator(ch))
{
while(!is_empty(&s1) && priority(peek(&s1))>=priority(ch))
*output++ = pop(&s1);
push(&s1,ch);
}
else
*output++ = ch;
}
while(!is_empty(&s1))
*output++ = pop(&s1);
*output = 0;
}

Here is the complete program

#include<stdio.h>
#include"stack.h"
int is_operator(char ch)
{
switch(ch)
{
case '+':
case '-':
case '/':
case '*':
case '%':
case '^':
return 1;
default : return 0;
}
}
int priority(char ch)
{
switch(ch)
{
case '+':
case '-':return 1;
case '/':
case '*':
case '%':return 2;
case '^':return 3;

default : return 0;
}
}

void convert(char *input, char *output)
{
struct stack s1;
s1.top = -1;
while(*input)
{
char ch = *input++;
char ch2;
if(ch=='(')
push(&s1,ch);
else if(ch==')')
{
while(!is_empty(&s1) && ( (ch=pop(&s1))!='('))
*output++ = ch;
}
else if(is_operator(ch))
{
while(!is_empty(&s1) && priority(peek(&s1))>=priority(ch))
*output++ = pop(&s1);
push(&s1,ch);
}
else
*output++ = ch;
}
while(!is_empty(&s1))
*output++ = pop(&s1);
*output = 0;
}

int main()
{
char infix[40],postfix[40];
printf("Enter infix expression:");
scanf("%s",infix);
convert(infix,postfix);
printf("the postfix expression is %s\n",postfix);
return 0;
}

The program uses a header file stack.h which has declarations of push, pop, is_empty and peek. It also has struct stack declaration and MAX.

The program used array based stack implementation. Here is charstack.c which has to be compiled along with the above program


#include<stdio.h>
#include"stack.h"
void push(struct stack *s, char val)
{
if( is_full(s))
printf("Stack overflow");
else
{
(s->top)++;
s->arr[s->top]=val;
}
}
int is_empty(struct stack *s)
{
return s->top==-1;
}
int is_full(struct stack *s)
{
return s->top>=MAX;
}
char pop(struct stack *s)
{
int val = 0;
if(is_empty(s))
printf("Stack empty");
else
{
char t = s->arr[s->top];
s->top--;
val = t;
}
return val;
}
char peek(struct stack *s)
{
if(is_empty(s))
printf("Stack empty");
else
return s->arr[s->top];
}


e.g.
Let me take simplest example
(A+B)*C

Character      Stack       Output
(                      (
A                     (               A
+                     (+            A
B                      (+           AB
)                       (              AB+
                                        AB+
*                       *              AB+
C                      *              AB+C
--------------------------------------------------------End of expression
                                        AB+C*


So now we have our postfix expression. Try this out for lengthier expressions yourself


                                    

Comments

Popular posts from this blog

Introduction to AVL tree

AVL tree is a balanced binary search tree where the difference between heights of two sub trees is maximum 1. Why balanced tree A binary tree is good data structure because search operation here is of the order of O(logn). But this is true if the tree is balanced - which means the left and right subtrees are almost equal in height. If not balanced, search operation will take longer.  In worst case, if the tree has only one branch, then search is of the order O(n). Look at this example.  Here all nodes have only right children.  To search a value in this tree, we need upto 7 iterations, which is O(n). So this tree is very very inefficient. One way of making the tree efficient is to, balance the tree and make sure that height of two branches of each node are almost equal. Height of a node Height of a node is the distance between the node and its extreme child.  In the above a diagram, height of 37 is 3 and height of left child of 37 is 0 and right child of 37 is 2. Bal...

Balanced brackets

Have you observed something? When ever you are writing code using any IDE, if you write mismatched brackets, immediately an error is shown by IDE. So how does IDE  know if an expression is having balanced brackets? For that, the expression must have equal number of opening and closing brackets of matching types and also they must be in correct order. Let us look at some examples (a+b)*c+d*{e+(f*g)}   - balanced (p+q*[r+u )] - unbalanced (p+q+r+s) ) - unbalanced (m+n*[p+q]+{g+h}) - balanced So we do we write a program to check if an expression is having balanced brackets? We do need to make use of stack to store the brackets. The algorithm is as follows Scan a character - ch from the expression If the character is opening bracket, push it to stack If the character is closing bracket pop a character from stack If popped opening bracket and ch are not of same type ( ( and ) or [ and ] ) stop the function and return false Repeat steps 2 and 3 till all characters are scanned. On...

Program to delete a node from linked list

How do you remove a node from a linked list? If you have to delete a node, first you need to search the node. Then you should find its previous node. Then you should link the previous node to the next node. If node containing 8 has to be deleted, then n1 should be pointing to n2. Looks quite simple. Isn't it? But there are at least two special cases you have to consider. Of course, when the node is not found. If the node is first node of the list viz head. If the node to be deleted is head node, then if you delete, the list would be lost. You should avoid that and make the second node as the head node. So it becomes mandatory that you return the changed head node from the function.   Now let us have a look at the code. #include<stdio.h> #include<stdlib.h> struct node { int data; struct node * next; }; typedef struct node * NODEPTR; NODEPTR create_node ( int value) { NODEPTR temp = (NODEPTR) malloc( size...