-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathInfix Evaluation in one go.cpp
94 lines (94 loc) · 2.26 KB
/
Infix Evaluation in one go.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include<iostream> //ONLY SINGLE DIGIT NUMBERS TO BE USED IN EXPRESSION
#include<stack>
#include<string>
using namespace std;
int Prec(char op)
{
switch(op)
{
case '+':
case '-': return 1;
case '*':
case '/': return 2;
case '^': return 3;
}
return -1;
}
int result(int a, char op, int b)
{
switch(op)
{
case '+':return a+b;
case '-':return a-b;
case '*':return a*b;
case '/':return a/b;
case '^':return a^b;
}
}
int infixEval(string in)
{
stack<char> operate;
stack<int> operand;
for(int i=0;i<in.length();i++)
{
if(isdigit(in[i]))
{
operand.push(in[i]-'0');
}
else if(in[i] == '(')
operate.push(in[i]);
else if(in[i] == ')')
{
while(operate.top()!='(')
{
int res;
int a = operand.top();
operand.pop();
int b = operand.top();
operand.pop();
char op = operate.top();
operate.pop();
res = result(a,op,b);
operand.push(res);
}
operate.pop();
}
else
{
while(!operate.empty() && Prec(in[i])<=Prec(operate.top()))
{
int res;
int a = operand.top();
operand.pop();
int b = operand.top();
operand.pop();
char op = operate.top();
operate.pop();
res = result(a,op,b);
operand.push(res);
}
operate.push(in[i]);
}
}
while(!operate.empty())
{
int res;
int b = operand.top();
operand.pop();
int a = operand.top();
operand.pop();
char op = operate.top();
operate.pop();
res = result(a,op,b);
operand.push(res);
}
return operand.top();
}
int main()
{
string infix;
cout<<"Enter the infix expression"<<endl;
cin>>infix;
cout<<"The value of expression is "<<infixEval(infix);
return 0;
}