forked from abbh07/DataStructure-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack-InfixToPostfix.cpp
169 lines (157 loc) · 2.16 KB
/
Stack-InfixToPostfix.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#include <iostream>
#include <cctype>
#define MAX 20
using namespace std;
class Stack
{
private:
int top;
int arr[MAX];
public:
Stack()
{
top = -1;
}
void push(int);
int pop();
int isOperand(char);
int precedence(char);
int infixToPostfix(char*);
int peek();
int isEmpty();
int evaluatePostfix(char*);
};
void Stack::push(int num)
{
if(top == MAX-1)
{
cout<<"Stack Overflow!\n";
return;
}
else
{
arr[++top] = num;
}
}
int Stack::pop()
{
if(top == -1)
{
return -1;
}
else
{
return arr[top--];
}
}
int Stack::isOperand(char ch)
{
if((ch>='a' && ch<='z')||(ch>='A' && ch<='Z') ||(ch>='1' && ch<='9'))
return 1;
else
return 0;
}
int Stack::precedence(char ch)
{
switch(ch)
{
case '+':
case '-':return 1;
case '/':
case '*':return 2;
case '^':return 3;
}
return -1;
}
int Stack::peek()
{
return arr[top];
}
int Stack::isEmpty()
{
if(top == -1)
return 1;
else
return 0;
}
int Stack::infixToPostfix(char inf[])
{
char post[MAX];
int j=0;
for(int i=0;inf[i] != '\0';i++)
{
if(isOperand(inf[i]))
{
post[j] = inf[i];
j++;
}
else if(inf[i] == '(')
{
push(inf[i]);
}
else if(inf[i] == ')')
{
while(isEmpty() != 1 && peek() != '(')
{
post[j] = pop();
j++;
}
pop();
}
else
{
while(isEmpty() != 1 && precedence(inf[i])<=precedence(peek()))
{
post[j] = pop();
j++;
}
push(inf[i]);
}
}
while(isEmpty() != 1)
{
post[j] = pop();
j++;
}
post[j] = '\0';
for(int i=0;post[i]!='\0';i++)
{
cout<<post[i];
}
cout<<endl;
}
int Stack::evaluatePostfix(char post[])
{
for(int i=0;post[i]!='\0';i++)
{
if(isdigit(post[i]))
push(post[i]-'0');
else
{
int val1 = pop();
int val2 = pop();
switch(post[i])
{
case '+':push(val2+val1);break;
case '-':push(val2-val1);break;
case '*':push(val2*val1);break;
case '/':push(val2/val1);break;
}
}
}
return pop();
}
int main()
{
Stack s;
char inf[MAX];
cout<<"Enter an infix string\n";
cin>>inf;
cout<<"Postfix string:\n";
s.infixToPostfix(inf);
cout<<"Enter the postfix string to be evaluated\n";
char arr[MAX];
cin>>arr;
cout<<"Result: "<<s.evaluatePostfix(arr);
return 0;
}