-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreeva.cpp
146 lines (145 loc) · 2.38 KB
/
preeva.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
// Postfix evaluation.
#include <iostream>
#include <math.h>
#include <string.h>
using namespace std;
#define MAX 30
int t1, t2, num;
class STACK
{
int top;
public:
int a[MAX];
STACK() { top = -1; }
bool push(int x);
int pop();
int peek();
bool isEmpty();
} d;
bool STACK ::push(int x)
{
if (top >= (MAX - 1))
{
cout << "Stack overflow";
return false;
}
else
{
a[++top] = x;
}
}
int STACK ::pop()
{
if (top < 0)
{
cout << "\nStack Underflow!" << endl;
return 0;
}
else
{
int x = a[top--];
return x;
}
}
int STACK ::peek()
{
if (top < 0)
{
cout << "\nThe stack is empty!" << endl;
}
else
{
int x = a[top];
return x;
}
}
bool STACK ::isEmpty()
{
return (top < 0);
}
void check(char o)
{
int ans;
switch (o)
{
case '+':
{
t2 = d.pop();
t1 = d.pop();
ans = t1 + t2;
d.push(ans);
break;
}
case '-':
{
t2 = d.pop();
t1 = d.pop();
ans = t1 - t2;
d.push(ans);
break;
}
case '/':
{
t2 = d.pop();
t1 = d.pop();
ans = t1 / t2;
d.push(ans);
break;
}
case '%':
{
t2 = d.pop();
t1 = d.pop();
ans = t1 % t2;
d.push(ans);
break;
}
case '*':
{
t2 = d.pop();
t1 = d.pop();
ans = t1 * t2;
d.push(ans);
break;
}
case '$':
{
t2 = d.pop();
t1 = d.pop();
ans = pow(t1, t2);
d.push(ans);
break;
}
default:
break;
}
}
void poeva(char p[])
{
int i = 0;
while (p[i] != '\0')
{
if ((p[i] >= 'a' && p[i] <= 'z') || (p[i] >= 'A' && p[i] <= 'Z'))
{
cout << "Enter value of " << p[i] << " :" << endl;
cin >> num;
d.push(num);
}
else
{
check(p[i]);
}
i++;
}
}
int main()
{
char str[20];
cout << "Enter prefix expression: " << endl;
cin >> str;
strrev(str);
poeva(str);
cout << "\nThe answer after evaluation is:" << endl;
cout << d.pop();
return 0;
}