برنامه تبدیل infix بهpostfixومحاسبه عبارت
include iostream.h
include conio.h
include stdlib.h
define max 30
class stack{
private:
char items[max];
int top;
public:
stack(){top=-1;}
stacktop(){return items[top];}
int empty()
{return (top==-1?1:0);}
int full()
{return (top==(max-1)?1:0);}
void push(char x)
{
if(full())
{
cout<<"stack is full";
return;
}
items[++top]=x;
return;
}
char pop()
{
if(empty())
{ cout<<"stack is empty";
return 0;
}
return (items[top--]);
}
};
int prio(char ch)
{
switch(ch)
{
case'(':return 1;break;
case'^':return 4;break;
case'*':return 3;break;
case'/':return 3;break;
case'+':return 2;break;
case'-':return 2;break;
}
}
int pow(int x,int y)
{
int w=1;
for(int i=0;i
return w;
}
struct point
{
int x,y;
};
int eval(int t,int v,char m)
{
int d;
switch(m)
{
case'+':d=(t+v);break;
case'-':d=(t-v);break;
case'/':d=(t/v);break;
case'*':d=(t*v);break;
case'^':d=(pow(t,v));break;
}
return d;
}
void main()
{
int z,k,y,t,v,h=0,j=0,x;
char m,a[max];
char infix[max];
char postfix[max];
stack s,q;
clrscr();
cout<<"Enter your infix;\n";
cin>>infix;
for(int i=0;(infix[i])!='\0';i++)
{
if(infix[i]=='(')
s.push(infix[i]);
else if(infix[i]==')')
{
while(s.stacktop()!='(')
postfix[j++]=s.pop();
if(s.stacktop()=='(')
s.pop();
}
else
if(infix[i]=='^'||infix[i]=='*' ||infix[i]=='+'||infix[i]=='/'||infix[i]=='-')
{
if(!(s.empty()))
{
int temp=0;
while(temp!=1)
if(prio(infix[i])>prio(s.stacktop()))
{
s.push(infix[i]);
temp=1;
}
else
{
postfix[j++]=s.pop();
}
}
else
s.push(infix[i]);
}
else
postfix[j++]=infix[i];
}
while(!(s.empty())) for(int b=0;postfix[b]!='\0';b++)
postfix[j++]=s.pop();
postfix[j++]='\0';
cout<<"postfix is:"<
{
if('0'<=(postfix[b])&&(postfix[b])<='9')
{
h=(postfix[b])-48;
q.push(h);
}
else
if((postfix[b])=='/'||(postfix[b])=='+'||(postfix[b])=='*'||(postfix[b])=='^'||(postfix[b])=='-')
if(!(q.empty()))
{
v=q.pop();
t=q.pop();
int c=eval(t,v,postfix[b]);
q.push(c);
}
else
q.push(postfix[b]);
}
y=q.pop();
cout<<"natigeh:"<