Hello I have written the code I was wondering is there a way to switch this code into running a different way. Please show it and please make it where it is easy to copy the code afterwards in c++. The code is intended to write infix to prefix notation. HERES THE CODE PLEASE REWRITE A DIFFERENT WAY. #include #include using namespace std; bool isOperator(char x) { return (!isalpha
Hello I have written the code I was wondering is there a way to switch this code into running a different way. Please show it and please make it where it is easy to copy the code afterwards in c++. The code is intended to write infix to prefix notation.
HERES THE CODE PLEASE REWRITE A DIFFERENT WAY.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
bool isOperator(char x) {
return (!isalpha(x) && !isdigit(x));
}
int getPriority(char x) {
if (x == '-' || x == '+')
return 1;
else if (x == '*' || x == '/')
return 2;
else if (x == '^')
return 3;
return 0;
}
string infixToPrefix(string infix) {
stack<char> operators;
stack<string> operands;
for (int i = 0; i < infix.length(); i++) {
if (infix[i] == '(') {
operators.push(infix[i]);
} else if (infix[i] == ')') {
while(!operators.empty() && operators.top() != '(') {
string op1 = operands.top();
operands.pop();
string op2 = operands.top();
operands.pop();
char op = operators.top();
operators.pop();
string temp = op + op1 + op2;
operands.push(temp);
}
operators.pop();
} else if(!isOperator(infix[i])) {
operands.push(string(1, infix[i]));
} else {
while(!operators.empty() && getPriority(infix[i]) <= getPriority(operators.top())) {
string op1 = operands.top();
operands.pop();
string op2 = operands.top();
operands.pop();
char op = operators.top();
operators.pop();
string temp = op + op1 + op2;
operands.push(temp);
}
operators.push(infix[i]);
}
}
while (!operators.empty()) {
string op1 = operands.top();
operands.pop();
string op2 = operands.top();
operands.pop();
char op = operators.top();
operators.pop();
string temp = op + op1 + op2;
operands.push(temp);
}
return operands.top();
}
int main() {
string s = "(A-B/C)*(A/K-L)";
cout << infixToPrefix(s);
return 0;
}
Step by step
Solved in 2 steps with 1 images