-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpression_evaluation.cpp
More file actions
118 lines (117 loc) · 2.08 KB
/
expression_evaluation.cpp
File metadata and controls
118 lines (117 loc) · 2.08 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include<bits/stdc++.h>
using namespace std;
int prio(char c)
{
if(c=='*' || c=='/')
{
return 2;
}
else if(c=='+' || c=='-')
{
return 1;
}
else
{
return -1;
}
}
string infixtopostfix(string s)
{
string res="";
stack<char> st;
for(int i=0;i<s.size();i++)
{
char c=s[i];
if((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9'))
{
res+=c;
}
else if(c=='(')
{
st.push('(');
}
else if(c==')')
{
while(st.top()!='(')
{
res+=st.top();
st.pop();
}
st.pop();
}
else
{
while(!st.empty() && (prio(st.top())>=prio(s[i])))
{
res+=st.top();
st.pop();
}
st.push(c);
}
}
while(!st.empty())
{
res+=st.top();
st.pop();
}
cout<<res<<"\n";
return res;
}
bool isoperator(char x)
{
if(x=='+' || x=='-' || x=='*' || x=='/')
return true;
return false;
}
int operation(int a,int b,char op)
{
int a1=a;
int b1=b;
// int a1=a-'0';
//int b1=b-'0';
if(op=='*')
{
return a1*b1;
}
else if(op=='/')
{
return b1/a1;
}
else if(op=='+')
{
return a1+b1;
}
else if(op=='-')
{
return b1-a1;
}
}
void evaluation(string p)
{
stack<int> st;
for(int i=0;i<p.size();i++)
{
if(isoperator(p[i]))
{
int a1=st.top();
st.pop();
int b1=st.top();
st.pop();
char op=p[i];
int a=operation(a1,b1,op);
st.push(a);
}
else
{
st.push(p[i]-'0');
}
}
cout<<st.top();
}
int main()
{
string str = "3+4*6-6" ;
string p=infixtopostfix(str);
evaluation(p);
return 0;
}