Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 4

#include<iostream.

h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
class infix
{
char *s,*t;
int top,i;
char stack[50];
public:
infix()
{
top=-1;
s=new char[50];
t=new char[50];
strcpy(stack,"");
i=0;
}
void setxpr(char *str)
{
strcpy(s,str);
}
void push(char c)
{
if(top==49)
cout<<"stack overflow";
else
{
top++;
stack[top]=c;
}
}
char pop()
{
if(top==-1)
{
cout<<"stack underflow";
return 0;
}
else
{
char item=stack[top];
top-=1;
return item;
}
}
void convert()
{
while(*s!='\0')
{
if((*s==' ')||(*s=='\t'))
{
s++;
continue;
}
if((isdigit(*s))||(isalpha(*s)))
{

while((isdigit(*s))||(isalpha(*s)))
{
*t=*s;
s++;
t++;
i++;
}
continue;
}
if(*s=='(')
{
push(*s);
s++;
continue;
}
if(*s==')')
{
char opr=pop();
while(opr!='(')
{
*t=opr;
t++;
i++;
opr=pop();
}
s++;
continue;
}
if(top!=-1)
{
char opr = pop();
if(priority(opr)>=priority(*s))
{
while(priority(opr)>=priority(*s))
{
*t=opr;
t++;
i++;
if(top!=-1)
opr=pop();
else
break;
}
push(*s);
s++;
continue;
}else
{

push(opr);
push(*s);
s++;
continue;
}
}
else
{
push(*s);
s++;
continue;
}
}
while(top!=-1)
{
char opr = pop();
*t=opr;
t++;
i++;
}
*t='\0';
}

int priority(char c)
{
if(c=='^')
return 3;
if((c=='*')||(c=='/')||(c=='%'))
return 2;
if((c=='+')||(c=='-'))
return 1;
else
return 0;
}
void show()
{for(;i>=0;i--)
{

cout<<*(t-i);
}
}
};
int main()
{
char st[50];
infix q;
cout<<"enter expr:";
cin.getline(st,50);

q.setxpr(st);
q.convert();
cout<<"\npostfix is ";
q.show();
return 0;
}

You might also like