This repository has been archived by the owner on Feb 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
make-bracket.cpp
109 lines (98 loc) · 2.46 KB
/
make-bracket.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
103
104
105
106
107
108
109
#include <bits/stdc++.h>
using namespace std;
//Driver program to test above functions
bool isOperand(char x) {
return (x >= '1' && x <= '9');
}
//Function to return precedence of operators
int prec(char c)
{
if(c == '^')
return 3;
else if(c == '*' || c == '/')
return 2;
else if(c == '+' || c == '-')
return 1;
else
return -1;
}
// The main function to convert infix expression
//to postfix expression
string infixToPostfix(string s)
{
stack<char> st;
st.push('N');
int l = s.length();
string ns;
for(int i = 0; i < l; i++)
{
// If the scanned character is an operand, add it to output string.
if((s[i] >= '1' && s[i] <= '9'))
ns+=s[i];
// If the scanned character is an ‘(‘, push it to the stack.
else if(s[i] == '(')
st.push('(');
// If the scanned character is an ‘)’, pop and to output string from the stack
// until an ‘(‘ is encountered.
else if(s[i] == ')')
{
while(st.top() != 'N' && st.top() != '(')
{
char c = st.top();
st.pop();
ns += c;
}
if(st.top() == '(')
{
char c = st.top();
st.pop();
}
}
//If an operator is scanned
else{
while(st.top() != 'N' && prec(s[i]) <= prec(st.top()))
{
char c = st.top();
st.pop();
ns += c;
}
st.push(s[i]);
}
}
//Pop all the remaining elements from the stack
while(st.top() != 'N')
{
char c = st.top();
st.pop();
ns += c;
}
return ns;
}
string infixConversion(string postfix) {
stack<string> infix;
for (int i=0; postfix[i]!='\0'; i++) {
if (isOperand(postfix[i])) {
string op(1, postfix[i]);
infix.push(op);
} else {
string op1 = infix.top();
infix.pop();
string op2 = infix.top();
infix.pop();
infix.push("("+op2+postfix[i]+op1 +")");
}
}
return infix.top();
}
int main()
{
string a;
cout << "Test 1 :";
cin >> a;
cout <<"Answer 1 :" <<infixConversion(infixToPostfix(a)) << "\n";
cout << "------------------------------------------" << "\n";
cout << "Test 2 :";
cin >> a;
cout <<"Answer 2 :" <<infixConversion(infixToPostfix(a)) << "\n";
return 0;
}