-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfix2Postfix.cpp
More file actions
95 lines (86 loc) · 1.79 KB
/
Infix2Postfix.cpp
File metadata and controls
95 lines (86 loc) · 1.79 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
#include <iostream>
#include <string>
using namespace std;
class Stack {
private:
char* stack;
int capacity;
int top;
void Double() {
capacity *= 2;
char* newstack = new char[capacity];
for (int i = 0; i < capacity / 2; i++) {
newstack[i] = stack[i];
}
delete[]stack;
stack = newstack;
}
public:
Stack() {
stack = new char[capacity];
capacity = 1;
top = -1;
}
bool Empty() {
return top == -1;
}
int Top() {
if (!Empty()) return stack[top];
}
void Push(char push) {
if (top == capacity - 1) Double();
stack[++top] = push;
}
void Pop() {
if (!Empty()) top--;
}
};
bool Operator(char i) {
if (i == '+' || i == '-' || i == '*' || i == '/') return true;
else return false;
}
bool Operand(char i) {
if (!Operator(i) && i != '(' && i != ')') return true;
else return false;
}
int Priority(char i) {
if (i == '*' || i == '/') return 1;
else if (i == '+' || i == '-') return -1;
else return 0;
}
string Infix2Posfix(string in) {
string out;
Stack opt;
opt.Push('N');
int l = in.length();
for (int i = 0; i < l; i++) {
if (Operand(in[i])) out += in[i];
else if (in[i] == '(') opt.Push(in[i]);
else if (in[i] == ')') { //pop remaining operator before (
while (opt.Top() != 'N' && opt.Top() != '(') {
out += opt.Top();
opt.Pop();
}
opt.Pop();
}
else if (Operator(in[i])) {
while (opt.Top() != 'N' && opt.Top() != '(' && Priority(opt.Top()) >= Priority(in[i])) {
out += opt.Top();
opt.Pop();
}
opt.Push(in[i]);
}
}
//pop out all remaining
while (opt.Top() != 'N') {
out += opt.Top();
opt.Pop();
}
return out;
}
int main() {
string in = "((A/B-C)+(D*E))-(A*C)";
cout<<Infix2Posfix(in)<<endl;
system("pause");
return 0;
}