Infix to Postfix conversion using stack

#include<stdio.h>
#include<conio.h>
#define max 50
typedef struct stack
{
char ar[max];
int top;
}st;

void push(st *,char);
char pop(st *);
char peek(st);
int isfull(st);
int isempty(st);

void intopost(char [],char []);
int getpriority(char);
int main()
{
char expr[max],res[max];

printf("enter the expression : ");
gets(expr);

intopost(expr,res);
printf("The postfix expression is : ");
puts(res);
getch();
}

void intopost(char expr[],char res[])
{
st s;
char ch;
int i,j;
s.top=-1;
for(i=0,j=0;expr[i]!='\0';i++)
{
if(expr[i]==' ')
continue;
else if(expr[i]=='(' || expr[i]=='{' || expr[i]=='[')
push(&s,expr[i]);
else if((expr[i]>=48 && expr[i]<=57) || (expr[i]>=65 && expr[i]<=90) || (expr[i]>=97 && expr[i]<=122))
res[j++]=expr[i];
else if(expr[i]=='+' || expr[i]=='-' || expr[i]=='*' || expr[i]=='/')
{
while(!isempty(s) && getpriority(expr[i])<=getpriority(peek(s)) && peek(s)!='(')
{
res[j++]=pop(&s);
}

push(&s,expr[i]);
}
else if(expr[i]==')' || expr[i]=='}' || expr[i]==']')
{
while(!isempty(s) && (ch=pop(&s))!='(')
{
res[j++]=ch;
}
}
else
{
printf("Expression not ok");
break;
}
}
if(!isempty(s))
{
while(!isempty(s) && (ch=peek(s))!='(')
res[j++]=pop(&s);
}
res[j]='\0';
}

void push(st *s,char ch)
{
s->ar[++s->top]=ch;
}

char pop(st *s)
{
return s->ar[s->top--];
}

char peek(st s)
{
return s.ar[s.top];
}

int isempty(st s)
{
if(s.top==-1)
return 1;
else
return 0;
}

int isfull(st s)
{
if(s.top==max-1)
return 1;
else
return 0;
}

int getpriority(char ch)
{
switch(ch)
{
case '+':
case '-': return 0;
case '*':
case '/':return 1;
}
}


/*
expected I/O :
enter the expression : (a*b)+c
The postfix expression is : ab*c+
*/

Comments

Popular posts from this blog

Pascal Triangle using 2D array

JAVA program to add two distance