Grupo
Estructuras de Datos: Pilas y Colas en C++
Ojetivo
1. Crear una pila para almacenar los operandos durante la evaluación de la expresión sufija.
2. Recorrer cada elemento de la expresión sufija:
- Si el elemento es un número, insertarlo en la pila.
- Si el elemento es un operador, extraer los dos primeros elementos de la pila, aplicar el operador y volver a insertar el resultado en la pila.
3. Una vez procesada la expresión completa, el resultado será el único número que quede en la pila.
4. Generar el resultado de la evaluación de la expresión.
Implementar una pila que calcule el valor de una expresión matemática mediante notación sufija.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include for input/output operations
#include <stack> // Include for stack data structure
#include <sstream> // Include for string stream (used to parse numbers)
#include <string> // Include for string handling
using namespace std;
// Function to perform arithmetic operations
int performOperation(int operand1, int operand2, char oper) {
// Perform the operation based on the operator
switch (oper) {
case '+': return operand1 + operand2; // Addition
case '-': return operand1 - operand2; // Subtraction
case '*': return operand1 * operand2; // Multiplication
case '/': return operand1 / operand2; // Division
default: return 0; // Default case (should not happen)
}
}
// Function to evaluate a postfix expression
int evaluatePostfix(string expression) {
stack<int> s; // Stack to store operands
stringstream ss(expression); // String stream to process each token
string token;
while (ss >> token) { // Read each token in the expression
if (isdigit(token[0])) { // If the token is a number
s.push(stoi(token)); // Push the number onto the stack
} else { // If the token is an operator
int operand2 = s.top(); // Get the second operand
s.pop(); // Remove the second operand
int operand1 = s.top(); // Get the first operand
s.pop(); // Remove the first operand
int result = performOperation(operand1, operand2, token[0]); // Perform the operation
s.push(result); // Push the result back onto the stack
}
}
return s.top(); // The result is the only number left on the stack
}
// Main function
int main() {
string expression = "3 4 + 2 * 7 /"; // Example postfix expression
cout << "Postfix Expression: " << expression << endl;
int result = evaluatePostfix(expression); // Evaluate the expression
cout << "Result: " << result << endl; // Output the result
return 0;
}
Salida
Postfix Expression: 3 4 + 2 * 7 /
Result: 2
Comparte este ejercicio C++