forked from rituburman/hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfixtopostfix.cpp
More file actions
132 lines (131 loc) · 1.54 KB
/
infixtopostfix.cpp
File metadata and controls
132 lines (131 loc) · 1.54 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
#include<iostream.h>
#include<conio.h>
#include<string.h>
class Stack
{
int stk[50];
int top;
public:
stack()
{
top=-1;
}
void push(int x)
{
if(top>49)
return;
stk[++top]=x;
}
void pop()
{
if(top<0)
return;
top--;
}
char peek()
{
return stk[top];
}
int isEmpty()
{
if(top==-1)return 1;
}
};
int getWeight(char ch)
{
switch(ch)
{
case '/':
case '*':
return 2;
case '+':
case '-':
return 1;
default:
return 0;
}
}
void infixpostfix(char s[],char ns[])
{
Stack st;
st.push('N');
int l=strlen(s);
int k=0;
for(int i=0;i<l;i++)
{
if((s[i]>='a'&& s[i]<='z')||(s[i]>='A'&& s[i]<='Z'))
{
ns[k]=s[i];
k++;
}
else if(s[i]=='(')
st.push('(');
else if(s[i]==')')
{
while(st.peek()!='N'&& st.peek()!='(')
{
char c=st.peek();
st.pop();
ns[k]=c;
k++;
}
if(st.peek()=='(')
{char c=st.peek();
st.pop();}
}
else
{
while(st.peek()!='N' && getWeight(s[i]<= getWeight(st.peek()))
{
char c=st.peek();
st.pop();
ns[k]=c;
k++;
}
st.push(s[i]);
}
}
while(st.peek()!='N')
{
char c=st.peek();
st.pop();
ns[k]=c;
k++;
}
cout<<ns;
}
void infixToPrefix(char s[],int l)
{
int i,k;
char rinfix[50].ns[50];
//Reverse infix
for(i=l-1,k=0;i>0;i--,k++)
{
rinfix[k]=s[i];
}
//Convert it to postfix
char post[50];
infixToPostfix(rimfix,post);
//Reverse Postfix to get Prefix
for(i=-1;i>0;i--)
{
cout<<post[i];
}
}
void main()
{
clrscr();
char infix[]="A+B";
int s=strlen(infix);
char postfix[50];
cout<<"Infix Expression:"<<infix;
cout<<"\nPostfix Expression:";
infixpostfix(infix,postfix);
for(int i=0; i<s;i++)
{
cout<<"prefix expression:";
}
infixtoprefix(infix,s);
getch();
}
}