-
Notifications
You must be signed in to change notification settings - Fork 27
/
Infix_Postfix.cpp
102 lines (94 loc) · 2.11 KB
/
Infix_Postfix.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
98
99
100
101
102
#include<iostream>
#include<deque>
#include<stack>
#include<strings.h>
using namespace std;
class Converter
{
stack<char> st;
deque<char> final_string{};
string str{};
public:
void get_string(void);
void calculate(void);
void show_result(void);
int is_operator(char);
int priority_check(char);
};
int Converter::priority_check(char op)
{
if(op=='*'||op=='/'||op=='%')
return 2;
if(op=='-'||op=='+')
return 1;
}
int Converter::is_operator(char ch)
{
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='%')
return 1;
return 0;
}
void Converter::show_result(void)
{
cout<<"\nPostfix Expression: ";
auto it = final_string.begin();
while(it!=final_string.end())
cout<<*(it++);
getchar();
}
void Converter::calculate(void)
{
for(int i=0;i<str.length();i++)
{
if(str[i]=='(')
{
st.push(str[i]);
continue;
}
if(str[i]==')')
{
while((st.top()!='(')&&(!st.empty()))
{
final_string.push_back(st.top());
st.pop();
}
st.pop();
continue;
}
if(!is_operator(str[i]))
final_string.push_back(str[i]);
else
{
if(st.empty()||(st.top()=='(')||(priority_check(str[i])>priority_check(st.top())))
st.push(str[i]);
else
{
while(1)
{
if(st.empty()||(st.top()=='('))
break;
final_string.push_back(st.top());
st.pop();
}
st.push(str[i]);
}
}
}
while(!st.empty())
{
final_string.push_back(st.top());
st.pop();
}
}
void Converter::get_string(void)
{
cout<<"\nEnter a Infix Expression without using spaces ";
getline(cin,str);
}
main()
{
Converter in_pos;
in_pos.get_string();
in_pos.calculate();
in_pos.show_result();
}