-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostfix.cpp
More file actions
118 lines (91 loc) · 2.83 KB
/
Copy pathpostfix.cpp
File metadata and controls
118 lines (91 loc) · 2.83 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 <string>
#include <stack>
using namespace std;
int getOpWeight(char op){
int weight = -1;
switch (op){
case '|' :
weight = 1;
break;
case '*' :
weight = 2;
break;
case '^' :
weight = 3;
break;
default:break;
}
return weight;
}
bool hasHigherPrec(char op1, char op2){
int op1Weight;
op1Weight = getOpWeight(op1);
int op2Weight;
op2Weight = getOpWeight(op2);
return op1Weight > op2Weight;
}
bool isOperator(char c) {
return (c == '|' || c == '*' || c == '^');
}
bool isOperand(char c){
return (c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c<= 'Z');
}
string infix2Postfix(string sentence){
stack<char> elems;
string postfix = "";
for (int i = 0;i<sentence.length() +1;i++){
if(sentence[i] == ' ' || sentence[i] == ',') continue;
else if(isOperand(sentence[i])){
postfix += sentence[i];
}
else if(isOperator(sentence[i])){
while (!elems.empty() && elems.top() != '(' && hasHigherPrec(elems.top(),sentence[i])){
postfix += elems.top();
elems.pop();
}
elems.push(sentence[i]);
}
else if(sentence[i] == '('){
elems.push(sentence[i]);
}
else if(sentence[i]==')'){
while(!elems.empty() && elems.top() != '(' ){
postfix += elems.top();
elems.pop();
}
elems.pop();
}
}
while (!elems.empty()){
postfix += elems.top();
elems.pop();
}
return postfix;
}
string fix (string sentence2){
string oracion = "";
for (int i =0;i<sentence2.size();i++){
if(sentence2[i]=='*'){
oracion += string() + "^";
}
if(isOperand(sentence2[i]) and isOperand(sentence2[i+1])){
oracion += string() + sentence2[i] + "*" ;
}
if(isOperand(sentence2[i]) and sentence2[i+1] == '('){
oracion += string() + sentence2[i] + "*" ;
}
if(sentence2[i]==')' and isOperand(sentence2[i+1])){
oracion += string() + sentence2[i] + "*" ;
}
if(sentence2[i]=='*' and isOperand(sentence2[i+1])){
oracion += string() +"*";
}
if(sentence2[i]=='*' and sentence2[i+1]=='('){
oracion += string() + "*";
}
else if (!(sentence2[i]=='*' and sentence2[i+1]=='(') and!(sentence2[i]=='*') and!(sentence2[i]=='^' and isOperand(sentence2[i+1])) and!(isOperand(sentence2[i]) and isOperand(sentence2[i+1]))and!(isOperand(sentence2[i]) and sentence2[i+1] == '(')and!((sentence2[i]==')' and isOperand(sentence2[i+1])))){
oracion += string() + sentence2[i];
}
}
return oracion;
}