-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathop_pred_21BCE3982.cpp
90 lines (68 loc) · 2.2 KB
/
op_pred_21BCE3982.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
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool isOperator(char c) {
return c == '+' || c == '*' || c == '(' || c == ')';
}
int getPrecedence(char op) {
if (op == '+' || op == '-')
return 1;
if (op == '*' || op == '/')
return 2;
return 0;
}
string parseExpression(const string& expression) {
stack<char> operators;
stack<string> operands;
for (char c : expression) {
if (isOperator(c)) {
while (!operators.empty() && operators.top() != '(' && getPrecedence(operators.top()) >= getPrecedence(c)) {
string operand2 = operands.top();
operands.pop();
string operand1 = operands.top();
operands.pop();
char op = operators.top();
operators.pop();
string result = operand1 + operand2 + op;
operands.push(result);
}
if (c == ')') {
operators.pop(); // Remove the corresponding opening bracket
while (!operators.empty() && operators.top() != '(') {
string operand2 = operands.top();
operands.pop();
string operand1 = operands.top();
operands.pop();
char op = operators.top();
operators.pop();
string result = operand1 + operand2 + op;
operands.push(result);
}
} else {
operators.push(c);
}
} else {
operands.push(string(1, c));
}
}
while (!operators.empty()) {
string operand2 = operands.top();
operands.pop();
string operand1 = operands.top();
operands.pop();
char op = operators.top();
operators.pop();
string result = operand1 + operand2 + op;
operands.push(result);
}
return operands.top();
}
int main() {
string expression;
cout << "Enter an expression: ";
getline(cin, expression);
string parsedExpression = parseExpression(expression);
cout << "Parsed expression: " << parsedExpression << endl;
return 0;
}