-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfix_to_postfix.cpp
140 lines (137 loc) · 1.71 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
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
#include<iostream>
#include<string.h>
using namespace std;
#define MAX 100
class Stack
{
public:
int top;
char a[MAX];
Stack(){
top=-1;
}
void push(char x);
char pop();
bool isEmpty();
int Top(){
return a[top];
}
};
void Stack :: push(char x)
{
if(top>=MAX-1)
{
cout<<"Stack overflow";
}
else
{
a[++top]=x;
}
}
char Stack :: pop()
{
if(top<0)
{
cout<<"stack underflow";
}
else
{
char p;
p=a[top--];
return p;
}
}
bool Stack :: isEmpty()
{
if(top<=-1)
{
return true;
}
else
return false;
}
/*int IsRightAssociative(char op)
{
if(op == '$') return true;
return false;
}*/
int getWeight(char p)
{
int weight = 0;
switch(p)
{
case '+':
case '-':
weight =1;
break;
case '*':
case '/':
case '%':
weight = 2;
break;
case '^':
weight = 3;
break;
return weight;
}
}
/*bool precedence(char o1 , char o2)
{
int w1 = getWeight(o1);
int w2 = getWeight(o2);
if(w1==w2)
{
if(IsRightAssociative(o1))
return false;
else
return true;
}
return (w1 > w2) ?true : false;
}*/
int main()
{
Stack s;
string str ="A-B/(C*D^E)";
string r=" ";
// str= strrev(ptr);
int i=0,j=0;
char c;
while(str[i] != '\0')
{
c = str[i];
if(c >= 65 && c <= 97)
{
//cout<<c;
r+=c;
}
else if(c =='+' || c=='-' || c=='%'|| c == '*'|| c=='/'|| c=='^')
{
if(!s.isEmpty() && s.Top()!='(' && getWeight(c)<= getWeight(s.Top()))
{
//cout<<s.pop();
r+=s.pop();
}
s.push(c);
}
if(c=='(')
{
s.push(c);
}
if(c == ')')
{
while(!s.isEmpty()&& s.Top()!='(')
//cout<<s.pop();
r+=s.pop();
s.pop();
}
i++;
}
while(!s.isEmpty())
{
char k=s.pop();
r+=k;
//cout<<k;
}
cout<<endl<<r;
return 0;
}