forked from a-r-nida/HactoberFest2020-Beginers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
infixToPostfix.cpp
81 lines (66 loc) · 1.52 KB
/
infixToPostfix.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
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int precedence (char ch) {
if (ch == '+' || ch == '-') {
return 1;
}
else if (ch == '*' || ch == '/') {
return 2;
}
else if (ch == '^') {
return 3;
}
else {
return 0;
}
}
string topostfix(string str){
stack <char> s;
string expression;
s.push('_');
for(int i = 0; i < str.length(); i++){
if (isalnum(str[i])) {
expression += str[i];
}
else if (str[i] == '(') {
s.push('(');
}
else if (str[i] == '^') {
s.push('^');
}
else if (str[i] == ')') {
while (s.top() != '(' && s.top() != '#') {
expression += s.top();
s.pop();
}
s.pop();
}
else {
if (precedence(str[i]) > precedence(s.top())) {
s.push(str[i]);
}
else {
while (s.top() != '_' && precedence(str[i]) <= precedence(s.top())) {
expression += s.top();
s.pop();
}
s.push(str[i]);
}
}
}
while (s.top() != '_') {
expression += s.top();
s.pop();
}
return expression;
}
int main()
{
string s;
cout << "Enter the expression: ";
cin >>s;
cout << topostfix(s);
return 0;
}