-
Notifications
You must be signed in to change notification settings - Fork 0
/
4postfix_exp.cpp
64 lines (53 loc) · 1.69 KB
/
4postfix_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
// 4. Evaluate Postfix Expression using Stack ADT.
// Theory:
// This code evaluates a postfix expression by iterating through each
// character of the expression and using a stack to perform the
// necessary arithmetic operations. It pushes operands onto the stack
// and when encountering an operator, it pops the required number of
// operands from the stack, performs the operation, and pushes the
// result back onto the stack.
#include <iostream>
#include <stack>
using namespace std;
int evaluate(const string& postfix)
{
stack<int> s;
for (char c : postfix)
{
if (isdigit(c))
{
s.push(c - '0');
}
else
{
int operand2 = s.top(); s.pop();
int operand1 = s.top(); s.pop();
switch(c)
{
case '+': s.push(operand1 + operand2);
break;
case '-': s.push(operand1 - operand2);
break;
case '*': s.push(operand1 * operand2);
break;
case '/': s.push(operand1 / operand2);
break;
}
}
}
return s.top();
}
int main()
{
string postfixexp;
cout << "enter postfix expression: ";
getline(cin, postfixexp);
cout << "result: " << evaluate(postfixexp) << endl;
return 0;
}
// Conclusion:
// The code efficiently evaluates postfix expressions using a
// stack-based approach, handling arithmetic operations such as
// addition, subtraction, multiplication, and division. It provides a
// straightforward implementation for expression evaluation, useful
// in various mathematical and computing applications.