-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpression.cpp
More file actions
81 lines (69 loc) · 1.42 KB
/
expression.cpp
File metadata and controls
81 lines (69 loc) · 1.42 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
#ifndef EXPRESSION_CPP
#define EXPRESSION_CPP
#include <iostream>
#include "expression.h"
#include "node.h"
#include "list.h"
#include <stack>
#include <sstream>
using namespace std;
Expression::Expression(Node* head){
this->head = head;
}
string Expression::infixString(){
return this->head->print_infix();
}
string Expression::prefixString(){
return this->head->print_prefix();
}
string Expression::postfixString(){
return this->head->print_postfix();
}
int Expression::stoi(string s){
stringstream ss(s);
int x;
ss >> x;
return x;
}
int Expression::Evaluate(){
string exp = this->head->print_postfix();
stack<int> integers;
for (int i = 0; i<exp.size(); i++){
char ch = exp[i];
if (isdigit(ch)){
integers.push(ch-'0');
}
else{
int second = integers.top();
integers.pop();
int first = integers.top();
integers.pop();
if (ch == '+')
integers.push(first + second);
else if (ch== '-')
integers.push(first - second);
else if (ch == '*')
integers.push(first * second);
else if (ch == '/')
integers.push(first / second);
}
}
return integers.top();
}
char Expression::Compare(Expression& ex){
int y = ex.Evaluate();
int x = Evaluate();
if (x > y){
cout << '>' << endl;
return '>';
}
else if (x < y){
cout << '<' << endl;
return '<';
}
else if (x == y){
cout << '=' << endl;
return '=';
}
}
#endif