-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimplement_stack_ADT.cpp
More file actions
97 lines (84 loc) · 2.63 KB
/
Copy pathimplement_stack_ADT.cpp
File metadata and controls
97 lines (84 loc) · 2.63 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
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
#include <iostream>
#include <stack>
#include <sstream>
#include <cctype>
// Stack class as an ADT
template <typename T>
class Stack {
private:
std::stack<T> data;
public:
// Function to push an element onto the stack
void push(T value) {
data.push(value);
}
// Function to pop an element from the stack
T pop() {
if (isEmpty()) {
throw std::runtime_error("Stack is empty");
}
T top = data.top();
data.pop();
return top;
}
// Function to check if the stack is empty
bool isEmpty() const {
return data.empty();
}
// Function to get the top element of the stack without popping it
T top() const {
if (isEmpty()) {
throw std::runtime_error("Stack is empty");
}
return data.top();
}
};
// Function to evaluate a postfix expression
template <typename T>
T evaluatePostfixExpression(const std::string& expression) {
Stack<T> stack;
std::istringstream iss(expression);
std::string token;
while (iss >> token) {
if (isdigit(token[0])) {
// If the token is a number, push it onto the stack
stack.push(static_cast<T>(std::stoi(token)));
} else {
// If the token is an operator, pop operands from the stack, perform the operation, and push the result back
T operand2 = stack.pop();
T operand1 = stack.pop();
if (token == "+") {
stack.push(operand1 + operand2);
} else if (token == "-") {
stack.push(operand1 - operand2);
} else if (token == "*") {
stack.push(operand1 * operand2);
} else if (token == "/") {
if (operand2 == 0) {
throw std::runtime_error("Division by zero");
}
stack.push(operand1 / operand2);
} else {
throw std::runtime_error("Invalid operator: " + token);
}
}
}
if (stack.isEmpty()) {
throw std::runtime_error("Invalid postfix expression");
}
return stack.pop();
}
int main() {
try {
// Example postfix expression: "5 3 4 * +"
std::string postfixExpression;
std::cout << "Enter a postfix expression (space-separated): ";
std::getline(std::cin, postfixExpression);
// Evaluate the postfix expression
int result = evaluatePostfixExpression<int>(postfixExpression);
std::cout << "Result: " << result << std::endl;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}