Repository navigation
Expand file tree
/
Copy pathPostFix and Infix.cpp
More file actions
158 lines (158 loc) · 4.08 KB
/
Copy pathPostFix and Infix.cpp
File metadata and controls
158 lines (158 loc) · 4.08 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#include<bits/stdc++.h>
using namespace std;
struct node
{
char c;
struct node* lchild;
struct node* rchild;
};
class Proposition{
public:string s1,ps;
struct node *head;
Proposition(string st){
s1=st;
head=NULL;
ps="";
}
string getPostfix(){
stack<char> st;
string s2;
char op[]={'(','>','V','^','~'};
for(int i=0;i<s1.length();i++)
{
if((int)s1[i]>=97&&(int)s1[i]<=122)
{
s2=s2+s1[i];
}
else
{
if(st.empty())
{
st.push(s1[i]);
}
else if(s1[i]=='(')
st.push(s1[i]);
else
{
int ind1=-1,ind2=-1;
for(int j=0;j<5;j++)
{
if(op[j]==s1[i])
ind1=j;
if(op[j]==st.top())
ind2=j;
}
if(ind1>=ind2)
{
st.push(s1[i]);
}
else
{
s2=s2+st.top();
st.pop();
if(ind1==-1)
{
while(st.top()!='(')
{
s2=s2+st.top();
st.pop();
}
st.pop();
}
else
st.push(s1[i]);
}
}
}
}
for(int i=0;!st.empty();i++)
{
s2=s2+st.top();
st.pop();
}
ps=s2;
return s2;
}
struct node* binaryTree(){
int n=ps.length();
char op[]={'>','V','^','~'};
int a[n]={0};
struct node * p[n];
for(int i=0;i<n;i++)
p[i] = (struct node*)malloc(sizeof(struct node));
for(int i=0;i<n;i++){
p[i]->c=ps[i];
p[i]->lchild=NULL;
p[i]->rchild=NULL;
}
for(int i=0;i<n;i++)
{
int k=0;
for(int j=0;j<4;j++)
if(ps[i]==op[j])
k=1;
if(ps[i]=='~')
{
int ind;
for(int j=i-1;j>=0;j--)
if(a[j]==0)
{
ind=j;
break;
}
a[ind]=1;
p[i]->rchild=p[ind];
}
else if(k)
{
int ind1=-1,ind2=-1;
int k1=0;
for(int j=i-1;j>=0;j--)
{
if(a[j]==0)
{
if(k1==0)
{
k1++;
ind1=j;
}
else
{
ind2=j;
break;
}
}
}
a[ind1]=1;
a[ind2]=1;
p[i]->rchild=p[ind1];
p[i]->lchild=p[ind2];
}
}
head=p[n-1];
//print(p[n-1]);
return p[n-1];
}
void print(struct node* nd){
if(nd==NULL)
return;
print(nd->lchild);
cout<<nd->c;
print(nd->rchild);
}
};
int main()
{
string s1;
cout<<"Enter a propositional Expression:";
cin>>s1;
Proposition p(s1);
string s2= p.getPostfix();
cout<<"Postfix of the given expression is: "<<s2<<endl;
struct node* head=NULL;
head=p.binaryTree();
cout<<head->lchild->c<<endl;
cout<<"Infix expression from the parse tree is: ";
p.print(head);
return 0;
}