C

Infix Expression to Post-fix (Reverse police) Notation

By Rabins Sharma Lamichhane

January 03, 2017

Here we just look out the code on Infix to Postfix expression notation.

It is also known as Reverse police method.

Find the full code snippet below.

Sample Code of Reverse Police Method

/* Infix expression to post-fix (Reverse police) notation RabinsXp.com */ #include<stdio.h> #include<ctype.h> #define MAX 100 typedef struct stack { int data[MAX]; int top;}stack; int priority(char x) { if(x == '(') return(0); if(x == '+' || x == '-') return(1); if(x == '*' || x == '/' || x == '%') return(2); if(x == '^') return (3); return(4); } void init(stack *s){ s->top=-1;} int empty(stack *s){ if(s->top==-1) return(1); else return(0);} int full(stack *s){ if(s->top==MAX-1) return(1); else return(0);} void push(stack *s,char x){ s->top=s->top+1; s->data[s->top]=x;} char pop(stack *s){ int x=s->data[s->top]; s->top=s->top-1; return(x); } char top(stack * s){ return(s->data[s->top]);} main() { stack s; char x; int token; init(&s); printf("nEnter infix expression:"); while((token=getchar())!='\n') { if(isalnum(token)) printf("%c",token); else if(token == '(') push(&s,'('); else { if(token == ')') while((x=pop(&s))!='(') printf("%c",x); else { while(priority(token)<=priority(top(&s)) && !empty(&s)) { x=pop(&s); printf("%c",x); } push(&s,token); } } } while(!empty(&s)) { x=pop(&s); printf("%c",x); } return (0); }

Share this: