-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEvaluate_postfix_exp.cpp
105 lines (96 loc) · 2.19 KB
/
Evaluate_postfix_exp.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
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
class CQStack
{
int maxSize; // size of stack array
int *stackArray;
int top; // top of stack
public:
// constructor
CQStack(int s)
{
maxSize = s; // set array size
stackArray = new int[maxSize]; // create array
top = -1; // no items yet
}
// Add element on the top of the stack
void push(int j)
{
if (isFull())
{
return;
}
else
{
stackArray[++top] = j; // increment top, insert item
}
}
// Remove element from the top of the stack
int pop()
{
if (isEmpty())
{
return -1;
}
else
{
int temp = stackArray[top--];
return temp; // access item, decrement top
}
}
// Return true is stack is empty
bool isEmpty()
{
return (top == -1);
}
// Return true if stack is full
bool isFull()
{
return (top == maxSize - 1);
}
};
/* pop(),push(int j) already defined in stack */
int evalPostfix(CQStack *stack, string exp) {
for (int i = 0; exp[i]; ++i) {
if (isdigit(exp[i]))
stack->push(exp[i] - '0');
else {
int val2 = stack->pop();
int val1 = stack->pop();
switch (exp[i]) {
case '+':
stack->push(val1 + val2);
break;
case '-':
stack->push(val1 - val2);
break;
case '*':
stack->push(val1 * val2);
break;
case '/':
stack->push(val1 / val2);
break;
case '^':
stack->push(pow(val1, val2));
break;
}
}
}
return stack->pop();
}
int main()
{
int t, n;
cin >> t;
while (t--)
{
string expr;
CQStack *stack = new CQStack(1000);
cin >> expr;
int result = evalPostfix(stack, expr);
cout << result << endl;
}
return 0;
}