forked from Ankita-Nandkumar-Patil/HactoberFest2021-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Infix_to_post_fix.cpp
97 lines (88 loc) · 2.08 KB
/
Infix_to_post_fix.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
91
92
93
94
95
96
97
#include <bits/stdc++.h>
using namespace std;
stack<char> infixStack;
int Precedence(char ch)
{
if (ch == '*' || ch == '/')
{
return 3;
}
else if (ch == '+' || ch == '-')
{
return 2;
}
else
{
return 0;
}
}
bool isoperator(char ch)
{
if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
return true;
}
else
{
return false;
}
}
string infix_to_postfix()
{
string Expression;
string Postfix_String;
char StoredChar;
char Stored_char2;
cout << "Enter the Expression: ";
cin >> Expression;
for (int i = 0; i < Expression.size(); i++)
{
if (isoperator(Expression[i]))
{
if (infixStack.empty())
{
infixStack.push(Expression[i]);
}
else if (Precedence(Expression[i]) > Precedence(infixStack.top()))
{
infixStack.push(Expression[i]);
}
else
{
while (true)
{
if ((Precedence(Expression[i]) < Precedence(infixStack.top())) || (Precedence(Expression[i]) == Precedence(infixStack.top())))
{
StoredChar = infixStack.top();
Postfix_String.push_back(StoredChar);
infixStack.pop();
if(infixStack.empty()){
break;
}
continue;
}
break;
}
infixStack.push(Expression[i]);
}
}
else
{
StoredChar = Expression[i];
Postfix_String.push_back(StoredChar);
}
}
while (!infixStack.empty())
{
Stored_char2 = infixStack.top();
Postfix_String.push_back(Stored_char2);
infixStack.pop();
}
return Postfix_String;
}
int main()
{
string final_String = infix_to_postfix();
cout << "The postfix Expression is: " << final_String;
return 0;
}