forked from AaqilSh/DSA-Collection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfix_to_postfix.cpp
95 lines (85 loc) · 1.35 KB
/
infix_to_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
#include<iostream>
#include<ctype.h>
using namespace std;
class infx_to_pofx{
char s[20], infx[20], pofx[20];
int top;
public :
infx_to_pofx()
{
top=-1;
}
void push(char);
char pop();
void getdata();
int pr(char);
void compute();
};
void infx_to_pofx :: getdata()
{
cout <<"enter the infix expression " << endl;
cin >> infx;
}
void infx_to_pofx :: push(char elem)
{
s[++top]=elem;
}
char infx_to_pofx :: pop()
{
return (s[top--]);
}
int infx_to_pofx :: pr(char elem)
{
switch(elem)
{
case '#' : return 0;
case '(' : return 1;
case '+' : return 2;
case '-' : return 2;
case '*' : return 3;
case '/' : return 3;
case '^' : return 4;
}
}
void infx_to_pofx :: compute()
{
char ch, elem;
int i=0, k=0;
push('#');
while( (ch=infx[i++]) != '\0' )
{
if (ch == '(' )
push(ch);
else if (ch == isalnum(ch))
pofx[k++]=ch;
else if (ch == ')')
{
while(s[top] != '(')
{
pofx[k++]=pop();
}
elem=pop();
}
else
{
while (pr(s[top]) >= pr(ch))
{
pofx[k++]=pop();
}
push(ch);
}
}
while ( s[top] != '#')
{
pofx[k++]=pop();
}
pofx[k]='\0';
cout << "postfix expression is " << pofx << endl;
}
int main()
{
infx_to_pofx obj;
obj.getdata();
obj.compute();
return 0;
}