//infix to postfix
#include<stdio.h>
#include<string.h>
#define SIZE 10
int pr(char op)
{
if(op=='*' || op=='/')
return 3;
if(op=='+' || op=='-')
return 2;
else
return 0;
}
char stack[SIZE];
int top=-1;
void push(char op)
{
stack[++top]=op;
}
char pop()
{
return stack[top--];
}
void rev_polish(char infix[],char postfix[])
{
int i,l,j=0;
char op;
l=strlen(infix);
infix[l]=')';
infix[l+1]='\0';
push('(');
for(i=0;infix[i]!='\0';i++)
{
if(isalpha(infix[i]))
{
postfix[j++]=infix[i];
continue;
}
if(infix[i]=='(')
{
push(infix[i]);
continue;
}
if(infix[i]==')')
{
while((op=pop())!='(')
postfix[j++]=op;
}
else
{
while(pr(infix[i])<=pr(stack[top]))
postfix[j++]=pop();
push(infix[i]);
}
}
postfix[j]='\0';
}
int main()
{
char infix[20],postfix[20];
printf("\nEnter the infix : ");
gets(infix);
rev_polish(infix,postfix);
printf("\nPostfix : %s",postfix);
return 0;
}
#include<stdio.h>
#include<string.h>
#define SIZE 10
int pr(char op)
{
if(op=='*' || op=='/')
return 3;
if(op=='+' || op=='-')
return 2;
else
return 0;
}
char stack[SIZE];
int top=-1;
void push(char op)
{
stack[++top]=op;
}
char pop()
{
return stack[top--];
}
void rev_polish(char infix[],char postfix[])
{
int i,l,j=0;
char op;
l=strlen(infix);
infix[l]=')';
infix[l+1]='\0';
push('(');
for(i=0;infix[i]!='\0';i++)
{
if(isalpha(infix[i]))
{
postfix[j++]=infix[i];
continue;
}
if(infix[i]=='(')
{
push(infix[i]);
continue;
}
if(infix[i]==')')
{
while((op=pop())!='(')
postfix[j++]=op;
}
else
{
while(pr(infix[i])<=pr(stack[top]))
postfix[j++]=pop();
push(infix[i]);
}
}
postfix[j]='\0';
}
int main()
{
char infix[20],postfix[20];
printf("\nEnter the infix : ");
gets(infix);
rev_polish(infix,postfix);
printf("\nPostfix : %s",postfix);
return 0;
}
1 comment:
Sir Pawan my applauds for you.....
Post a Comment