Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Could someone correct my mistake in my Java code? The following code is used to convert an infix expression to a prefix expression, however, when

Could someone correct my mistake in my Java code?

The following code is used to convert an infix expression to a prefix expression, however, when parentheses are introduced in the expression, I receive an incorrect expression as an output as well as an occasional "null" within the expression. Like: /+(null(null452

(Link to a pastebin of the code to help) https://pastebin.com/raw/5EL38c61

// takes an infix expression and returns prefix form of the infix // expression private static String infixToPrefix(String infix) { Stack operators = new Stack(); Stack operands = new Stack(); for (int i = 0; i < infix.length(); i++) { if (infix.charAt(i) == '(') { operators.push(infix.charAt(i)); } else if (infix.charAt(i) == ')') { while (!operators.isEmpty() && operators.peekTop() != '(') { String op1 = operands.peekTop(); operands.pop(); String op2 = operands.peekTop(); operands.pop(); char op = operators.peekTop(); operators.pop(); String tmp = op + op2 + op1; operands.push(tmp); } operators.pop(); } else if (!isOperator(infix.charAt(i))) { operands.push(infix.charAt(i) + ""); } else { while (!operators.isEmpty() && getInfixPriority(infix.charAt(i)) <= getInfixPriority(operators.peekTop())) { String op1 = operands.peekTop(); operands.pop(); String op2 = operands.peekTop(); operands.pop(); char op = operators.peekTop(); operators.pop(); String tmp = op + op2 + op1; operands.push(tmp); } operators.push(infix.charAt(i)); } } while (!operators.isEmpty()) { String op1 = operands.peekTop(); operands.pop(); String op2 = operands.peekTop(); operands.pop(); char op = operators.peekTop(); operators.pop(); String tmp = op + op2 + op1; operands.push(tmp); } return operands.peekTop(); }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions