-
Notifications
You must be signed in to change notification settings - Fork 141
/
Postfix to Infix.cpp
53 lines (47 loc) · 823 Bytes
/
Postfix to Infix.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
// CPP program to find infix for
// a given postfix.
#include <bits/stdc++.h>
using namespace std;
bool isOperand(char x)
{
return (x >= 'a' && x <= 'z') ||
(x >= 'A' && x <= 'Z');
}
// Get Infix for a given postfix
// expression
string getInfix(string exp)
{
stack<string> s;
for (int i=0; exp[i]!='\0'; i++)
{
// Push operands
if (isOperand(exp[i]))
{
string op(1, exp[i]);
s.push(op);
}
// We assume that input is
// a valid postfix and expect
// an operator.
else
{
string op1 = s.top();
s.pop();
string op2 = s.top();
s.pop();
s.push("(" + op2 + exp[i] +
op1 + ")");
}
}
// There must be a single element
// in stack now which is the required
// infix.
return s.top();
}
// Driver code
int main()
{
string exp = "ab*c+";
cout << getInfix(exp);
return 0;
}