Thursday 22 August 2019

Finalized without bounds infix to postfix

#include<stdio.h>
#include <process.h>
#define MAX 50
char stack[MAX];
int top=-1;
int getpriority(char);
void push(char);
char pop();
main()
{
char infix[50],temp,ch,postfix[50];
int i=0,j=0;
printf("enter the infix expression\n");
scanf("%s",&infix);
while(infix[i] != '\0')
{
ch=infix[i];
if(ch == '(')
push(ch);
else if(ch == ')')
{
while(stack[top]!='(')
postfix[j++]=pop();
temp=pop();// popping the (
}
else if(isdigit(ch)||isalpha(ch))
postfix[j++]=ch;
else
{
while(getpriority(stack[top])>=getpriority(ch))
postfix[j++]=pop();
push(ch);
}
i++;
}
while(top != -1)
postfix[j++]=pop();
postfix[j]='\0';
puts(postfix);
}
int getpriority(char ch)
{
if( ch == '*'|| ch == '/'|| ch == '%')
return 2;
else if(ch == '+' || ch == '-')
return 1;
else
return 0;
}
void push(char item)
{
if(top == MAX-1)
{
printf("stack is full");
return;
}
top=top+1;
stack[top]=item;
}

char pop()
{
if(top == -1)
{
printf("stack empty");
return;
}
char temp;
temp=stack[top];
top=top-1;
return temp;
}

No comments:

Post a Comment