Grupo
Estructuras de Datos: Pilas y Colas en C++
Ojetivo
1. Escriba un programa que lea una expresión infija.
2. Use una pila para convertir la expresión infija en una expresión sufija.
3. Implemente la precedencia de operadores para garantizar una conversión correcta.
4. Genere la expresión sufija resultante.
Desarrolle un programa que convierta una expresión infija en una sufija usando una pila.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include for input/output operations
#include <stack> // Include for stack data structure
#include <cctype> // Include for isdigit and isalpha functions
#include <string> // Include for string handling
using namespace std;
// Function to check if a character is an operator
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
// Function to determine the precedence of operators
int precedence(char c) {
if (c == '+' || c == '-') return 1;
if (c == '*' || c == '/') return 2;
return 0;
}
// Function to convert infix expression to postfix
string infixToPostfix(string infix) {
stack<char> s; // Stack to store operators
string postfix = ""; // String to store the postfix expression
for (int i = 0; i < infix.length(); i++) {
char c = infix[i];
// If the character is an operand (letter or digit), add it to the postfix expression
if (isalnum(c)) {
postfix += c;
}
// If the character is an open parenthesis, push it to the stack
else if (c == '(') {
s.push(c);
}
// If the character is a closing parenthesis, pop from the stack to the postfix expression until an open parenthesis is found
else if (c == ')') {
while (!s.empty() && s.top() != '(') {
postfix += s.top();
s.pop();
}
s.pop(); // Pop the open parenthesis
}
// If the character is an operator, pop operators with higher or equal precedence and add them to the postfix expression
else if (isOperator(c)) {
while (!s.empty() && precedence(s.top()) >= precedence(c)) {
postfix += s.top();
s.pop();
}
s.push(c); // Push the current operator to the stack
}
}
// Pop any remaining operators from the stack
while (!s.empty()) {
postfix += s.top();
s.pop();
}
return postfix;
}
// Main function
int main() {
string infix;
cout << "Enter an infix expression: ";
getline(cin, infix); // Read the entire line as an infix expression
string postfix = infixToPostfix(infix); // Convert the infix expression to postfix
cout << "Postfix expression: " << postfix << endl; // Output the result
return 0;
}
Salida
Enter an infix expression: A+(B*C-D)
Postfix expression: ABC*D-+
Comparte este ejercicio C++