-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluation of infix to postfix.cpp
126 lines (126 loc) · 1.53 KB
/
evaluation of 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
#include <iostream>
#include<string>
using namespace std;
class stack
{
private:
int len=100;
char arr[100];
public:
int top;
stack()
{
top=-1;
}
void push(char);
char pop();
void display();
char top_ele();
};
int postfix_eval(string post);
int main()
{
string exp;
cout<<"Enter the Expression "<<endl;
getline(cin,exp);
int required = postfix_eval(exp);
cout<<required<<endl;
}
void stack :: push(char x)
{
int check = top+1;
try
{
if(check>=len-1)
{
throw top;
}
else
{
top++;
arr[top]=x;
}
}
catch(int)
{
cout<<"Stack Overflow"<<endl;
}
}
char stack :: pop()
{
int check = top-1;
try
{
if(check<-1)
{
throw top;
}
else
{
top--;
return arr[top+1];
}
}
catch(int)
{
cout<<"Stack Underflow"<<endl;
}
}
void stack :: display()
{
cout<<"Element at "<<top<<" position is "<<arr[top]<<endl;
}
char stack :: top_ele()
{
return arr[top];
}
int postfix_eval(string post)
{
post.push_back(')');
int i=0;
stack numb;
while(post.at(i) != ')')
{
if((post.at(i) >= '0'&& post.at(i)<= '9'))
{
numb.push(post.at(i));
}
else if((post.at(i) == '+')||(post.at(i) == '-')||
(post.at(i) == '/')||(post.at(i) == '*'))
{ int res;
int a,b;
numb.push(post.at(i));
switch(numb.pop())
{
case '+':
a = numb.pop()-'0';
b = numb.pop()-'0';
res = a+b;
break;
case '-':
a = numb.pop()-'0';
b = numb.pop()-'0';
res = a - b;
break;
case '/':
a = numb.pop()-'0';
b = numb.pop()-'0';
res = a/b;
break;
case '*':
a = numb.pop()-'0';
b = numb.pop()-'0';
res = a*b;
break;
case'^':
a = numb.pop()-'0';
b = numb.pop()-'0';
res = a^b;
}
numb.push(res);
}
i++;
}
int value = numb.pop();
return value;
}