Rules For Converting An Infix Expression To A Prefix Expression and Codes
Rules For Converting An Infix Expression To A Prefix Expression and Codes
Finally, reverse the resulting postfix expression to get the correct prefix
expression.
Original infix: A + B * C
Reversed expression: C * B + A
Step 1
Reverse the Infix Expression
2. Next character D
Output Postfix: D
3. Next character -
Postfix: D C -
Stack: (empty)
6. Next character *
7. Next character (
8. Next character B
9. Next character +
A closing parenthesis means we pop the + operator from the stack and
add it to the postfix expression
Postfix: D C - B A +
Stack: *
Finally, we pop the * operator from the stack and add it to the postfix
expression:
Postfix: D C - B A + *
Now, reverse the postfix expression D C - B A + * to obtain the final prefix expression
*+AB-CD
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char infix[] = "A+B*(C^D-E)^(F+G*H)-I"; // Example complex expression
infixToPostfix(infix); // Convert the expression
return 0;
}
#include <iostream>
#include <cstring>
#include <cctype> // For isdigit()
#include <stack> // Using stack from STL
using namespace std;
// Function to check if a character is an operator
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
// Function to define precedence of operators
int precedence(char c) {
if (c == '^') return 3;
if (c == '*' || c == '/') return 2;
if (c == '+' || c == '-') return 1;
return 0;
}
// Function to reverse the string
string reverseString(string s) {
string reversed = s;
int n = reversed.length();
for (int i = 0; i < n / 2; i++) {
swap(reversed[i], reversed[n - i - 1]);
}
return reversed;
}
// Function to convert infix to postfix
string infixToPostfix(string infix) {
stack<char> st;
string postfix = "";
for (int i = 0; i < infix.length(); i++) {
char ch = infix[i];
// If it's an operand, add it to the postfix expression
if (isalnum(ch)) {
postfix += ch;
}
// If it's an opening parenthesis, push it to the stack
else if (ch == '(') {
st.push(ch);
}
// If it's a closing parenthesis, pop until we find an opening parenthesis
else if (ch == ')') {
while (!st.empty() && st.top() != '(') {
postfix += st.top();
st.pop();
}
st.pop(); // Pop the '('
}
// If it's an operator, pop operators of higher or equal precedence
else if (isOperator(ch)) {
while (!st.empty() && precedence(st.top()) >= precedence(ch)) {
postfix += st.top();
st.pop();
}
st.push(ch);
}
}
// Pop any remaining operators from the stack
while (!st.empty()) {
postfix += st.top();
st.pop();
}
return postfix;
}