-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathpostfix.cpp
More file actions
57 lines (49 loc) · 1.3 KB
/
postfix.cpp
File metadata and controls
57 lines (49 loc) · 1.3 KB
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
#include <iostream>
#include <string>
#include <stack>
using namespace std;
// Function to evaluate a given postfix expression
int evalPostfix(string exp)
{
// create an empty stack
stack<int> stack;
// traverse the given expression
for (char c: exp)
{
// if the current character is an operand, push it into the stack
if (c >= '0' && c <= '9') {
stack.push(c - '0');
}
// if the current character is an operator
else {
// remove the top two elements from the stack
int x = stack.top();
stack.pop();
int y = stack.top();
stack.pop();
// evaluate the expression 'x op y', and push the
// result back to the stack
if (c == '+') {
stack.push(y + x);
}
else if (c == '-') {
stack.push(y - x);
}
else if (c == '*') {
stack.push(y * x);
}
else if (c == '/') {
stack.push(y / x);
}
}
}
// At this point, the stack is left with only one element, i.e.,
// expression result
return stack.top();
}
int main()
{
string exp = "138*+";
cout << evalPostfix(exp);
return 0;
}