Group
Data Structures: Stacks, Queues in C++
Objective
1. Implement a stack to hold values (either true or false) during evaluation.
2. Read a logical expression containing operators: AND (&&), OR (||), and NOT (!).
3. Use the stack to evaluate the expression by processing the operands and operators one by one.
4. After processing all operators and operands, output the final result as true or false.
5. Handle basic logical expressions with proper operator precedence.
Implement a stack to evaluate logical expressions.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include for input/output operations
#include <stack> // Include for stack operations
#include <string> // Include for string manipulations
#include <sstream> // Include for stringstream operations
using namespace std;
// Function to evaluate logical expressions
bool evaluateLogicalExpression(string expr) {
stack s; // Stack to store boolean values (true/false)
stringstream ss(expr); // Stringstream to process the expression
string token; // To store individual tokens (operand or operator)
// Process each token in the expression
while (ss >> token) {
if (token == "true") {
s.push(true); // Push true onto the stack
} else if (token == "false") {
s.push(false); // Push false onto the stack
} else if (token == "&&") {
bool b2 = s.top(); s.pop(); // Pop the second operand
bool b1 = s.top(); s.pop(); // Pop the first operand
s.push(b1 && b2); // Perform AND operation and push the result
} else if (token == "||") {
bool b2 = s.top(); s.pop(); // Pop the second operand
bool b1 = s.top(); s.pop(); // Pop the first operand
s.push(b1 || b2); // Perform OR operation and push the result
} else if (token == "!") {
bool b = s.top(); s.pop(); // Pop the operand
s.push(!b); // Perform NOT operation and push the result
}
}
// Return the final result (the top element of the stack)
return s.top();
}
// Main function to test the logical expression evaluation
int main() {
string expr = "true false && true || ! false &&"; // Example logical expression
// Evaluate the expression
bool result = evaluateLogicalExpression(expr);
// Output the result
cout << "Result of the logical expression: " << (result ? "true" : "false") << endl;
return 0;
}
Output
Result of the logical expression: true