#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
class stack
{ public:
int t,arr1[20],m,e[2],top1,top2,i;
char a[50],arr2[20];
void pus1(int p);
void pus2(char q);
int pop1();
char pop2();
void check(char w);
};
void stack::pus1(int p)
{arr1[++top1]=p;
}
void stack::pus2(char q)
{arr2[++top2]=q;
}
void stack::check(char w)
{switch(w)
{case '+':
case '-':if(top2>-1)
pop2();
else
pus2(w);
break;
case '*':
case '/':if(arr2[top2]=='*' || arr2[top2]=='/')
pop2();
else
pus2(w);
break;
}
}
int stack::pop1()
{e[0]=arr1[top1--];
e[1]=arr1[top1--];
if(arr2[top2]=='-')
m=e[1]-e[0];
else if(arr2[top2]=='+')
m=e[1]+e[0];
else if(arr2[top2]=='*')
m=e[1]*e[0];
else
m=e[1]/e[0];
top2--;
pus1(m);
}
char stack::pop2()
{pop1();
check(a[i]);
}
int main()
{stack s;
s.top1=-1;
s.top2=-1;
int j,z;
cout<<"Enter the infix expression:\n";
cin.getline(s.a,50);
j=strlen(s.a);
for(s.i=0;s.i<j;s.i++)
{if(s.a[s.i]=='-' || s.a[s.i]=='+' || s.a[s.i]=='*' || s.a[s.i]=='/')
{s.check(s.a[s.i]);
}
else
{s.t=s.a[s.i];
s.t-=48;
s.pus1(s.t);
}
}
z=s.top2;
for(s.i=0;s.i<=z;s.i++)
{s.pop1();
}
cout<<"Hence the ans is:\n";
cout<<s.arr1[0];
}
#include<cstring>
#include<cstdlib>
using namespace std;
class stack
{ public:
int t,arr1[20],m,e[2],top1,top2,i;
char a[50],arr2[20];
void pus1(int p);
void pus2(char q);
int pop1();
char pop2();
void check(char w);
};
void stack::pus1(int p)
{arr1[++top1]=p;
}
void stack::pus2(char q)
{arr2[++top2]=q;
}
void stack::check(char w)
{switch(w)
{case '+':
case '-':if(top2>-1)
pop2();
else
pus2(w);
break;
case '*':
case '/':if(arr2[top2]=='*' || arr2[top2]=='/')
pop2();
else
pus2(w);
break;
}
}
int stack::pop1()
{e[0]=arr1[top1--];
e[1]=arr1[top1--];
if(arr2[top2]=='-')
m=e[1]-e[0];
else if(arr2[top2]=='+')
m=e[1]+e[0];
else if(arr2[top2]=='*')
m=e[1]*e[0];
else
m=e[1]/e[0];
top2--;
pus1(m);
}
char stack::pop2()
{pop1();
check(a[i]);
}
int main()
{stack s;
s.top1=-1;
s.top2=-1;
int j,z;
cout<<"Enter the infix expression:\n";
cin.getline(s.a,50);
j=strlen(s.a);
for(s.i=0;s.i<j;s.i++)
{if(s.a[s.i]=='-' || s.a[s.i]=='+' || s.a[s.i]=='*' || s.a[s.i]=='/')
{s.check(s.a[s.i]);
}
else
{s.t=s.a[s.i];
s.t-=48;
s.pus1(s.t);
}
}
z=s.top2;
for(s.i=0;s.i<=z;s.i++)
{s.pop1();
}
cout<<"Hence the ans is:\n";
cout<<s.arr1[0];
}
No comments:
Post a Comment