-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprccd.cpp
More file actions
96 lines (82 loc) · 1.9 KB
/
prccd.cpp
File metadata and controls
96 lines (82 loc) · 1.9 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
#include <bits/stdc++.h>
using namespace std;
#define STACKSIZE 50
struct stk {
char Item[STACKSIZE];
int Top;
};
struct stk S;
void Initialize() {
S.Top = -1;
}
bool IsEmpty() {
return (S.Top == -1);
}
void Push(char x) {
if (S.Top == (STACKSIZE - 1)) {
cout << "Stack Overflow";
exit(1);
} else {
S.Top++;
S.Item[S.Top] = x;
}
}
char Pop() {
if (IsEmpty()) {
cout << "Stack Underflow";
exit(1);
} else {
char x = S.Item[S.Top];
S.Top--;
return x;
}
}
char StackTop() {
return S.Item[S.Top];
}
bool Prcd(char op1, char op2) {
if (op1 == '(' || op2 == '(') return false;
if (op1 == '^') {
// ^ is right associative
if (op2 == '^') return false;
else return true;
} else if (op1 == '*' || op1 == '/' || op1 == '%') {
if (op2 == '^') return false;
else return true;
} else if (op1 == '+' || op1 == '-') {
if (op2 == '+' || op2 == '-') return true;
else return false;
}
return false;
}
int main() {
Initialize();
char Infix[100];
cin >> Infix;
string Postfix;
int i = 0;
while (Infix[i] != '\0') {
char symbol = Infix[i];
i++;
if (isalnum(symbol)) {
Postfix.push_back(symbol);
} else if (symbol == '(') {
Push(symbol);
} else if (symbol == ')') {
while (!IsEmpty() && StackTop() != '(') {
Postfix.push_back(Pop());
}
Pop();
} else{
while (!IsEmpty() && Prcd(StackTop(), symbol)) {
Postfix.push_back(Pop());
}
Push(symbol);
}
}
while (!IsEmpty()) {
Postfix.push_back(Pop());
}
cout << Postfix;
return 0;
}