#include<stdio.h>
#include<conio.h>
#define max 20
//To create structure stack
typedef struct STACK
{
char item[max];
int top;
}stack;
//To define functions
void push(stack*,char);
char pop(stack*);
int isfull(int);
int isempty(int);
void convertpos(char[]);
int priority(char);
void main()
{
char infix[80];
printf("\nEnter infix: ");
gets(infix);
convertpos(infix);
getch();
}
//To add elements is stack
void push(stack*s,char data)
{
if(isfull(s->top))
{
printf("stack is full.");
}
else
{
s->top=s->top+1;
s->item[s->top]=data;
}
}
//To check stack is empty or not
int isfull(int top)
{
if(top==max-1)
return 1;
else
return 0;
}
//To remove elements from stack
char pop(stack*s)
{
char data;
if(isempty(s->top))
printf("stack is empty.");
else
{
data=s->item[s->top];
s->top=s->top-1;
}
return data;
}
//To check stack is empty or not
int isempty(int top)
{
if(top==-1)
return 1;
else
return 0;
}
//To convert infix expression to postfix expression
void convertpos(char infix[])
{
int pos=0,i=0;
char sym,temp,postfix[max];
stack s;
s.top=-1;
push(&s,'#');
while(infix[i]!='\0')
{
sym=infix[i];
switch(sym)
{
case '(':push(&s,sym);break;
case ')':temp=pop(&s);
while(temp!='(')
{
postfix[pos]=temp;
pos++;
temp=pop(&s);
}
break;
case '+':
case '-':
case '*':
case '/':
case '^':
case '%':while(priority(s.item[s.top])<=priority(sym))
{
temp=pop(&s);
postfix[pos]=temp;
pos++;
}
push(&s,sym);break;
default :postfix[pos]=sym;
pos++;
break;
}i++;
}
temp=pop(&s);
while(temp!='#')
{
postfix[pos]=temp;
pos++;
temp=pop(&s);
}
postfix[pos]='\0';
printf("\npostfix %s",postfix);
}
//To check the priority of elements in stack
int priority(char sym)
{
if(sym=='^'||sym=='%')
return 0;
if(sym=='*'||sym=='/'||sym=='%')
return 1;
if(sym=='+'||sym=='-')
return 2;
else
return 3;
}
0 Comments