-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheval.cpp
More file actions
111 lines (101 loc) · 1.89 KB
/
eval.cpp
File metadata and controls
111 lines (101 loc) · 1.89 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
#include <iostream>
using namespace std;
class stack{
public:
struct Node{
int data;
Node *next;
};
stack(){
head = NULL;
}
void push(int val){
Node* n = new Node();
n->data=val;
n->next = head;
head = n;
}
void display(){
Node *n;
n=head;
while(n!=NULL){
cout<<n->data;
n=n->next;
}
}
int pop(){
Node *n = head;
head=head->next;
return n->data;
}
int top(){
return head->data;
}
bool empty(){
return head==NULL;
}
private:
Node* head;
};
bool isOp(char a){
return a=='*' || a=='/' ||a=='+' ||a== '-';
}
bool isNum(char a){
return a>='0' && a<='9';
}
int applyOp(char op, int b, int a){
switch (op){
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw runtime_error("Cannot divide by zero");
return a / b;
}
return 0;
}
bool hasPrecedence(char op1, char op2){
if (op2 == '(' || op2 == ')')
return false;
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
return true;
}
int main(){
stack val;
stack op;
string exp = "100 * 2 + 12 -2";
string num ="";
int inum;
int i=0;
for(int i=0; i<exp.size();i++){
if(exp[i]==' ') continue;
if(isNum(exp[i])) num=num+exp[i];
else if(exp[i]=='(') op.push(exp[i]);
else if(exp[i]==')'){
while(op.top()!='('){
val.push(applyOp(op.pop(), val.pop(), val.pop()));
}
op.pop();
}
else if(isOp(exp[i])){
val.push(stoi(num));
while(!op.empty() && hasPrecedence(exp[i],op.top())){
val.push(applyOp(op.pop(),val.pop(), val.pop()));
}
op.push(exp[i]);
num="";
}
}
val.push(stoi(num));
while(!op.empty()){
val.push(applyOp(op.pop(), val.pop(), val.pop()));
}
cout<<val.pop();
return 0;
}