Question: This code needs to do infix to prefix. However for some reason it is doing infix to postfix. Where am i doing wrong? Please supply

This code needs to do infix to prefix. However for some reason it is doing infix to postfix. Where am i doing wrong? Please supply code. Java language.

"1 + 2" is coming out as "1.0 2.0 +"

public DSQueue infixToPrefix(DSQueue infix) {

DSStack myStack = new DSStack();

DSQueue resultQueue = new DSQueue();

for (Node tempNode = infix.list.head; tempNode != null; tempNode = tempNode.next)

{

//create a char to check later on if this char is paren, operator or operand

char firstChar = tempNode.getToken().toString().charAt(0);

//check if firstChar is number (operand)

if (Character.isJavaIdentifierStart(firstChar)

|| Character.isDigit(firstChar))

{

//put it into the queue if it is a number

resultQueue.offer(tempNode.getToken());

}

//check if firstChar is an operator

if (firstChar == '+' || firstChar == '-' ||

firstChar == '/' ||firstChar == '*')

{

//take the operators from the stack and put it into the queue until

//the top of the stack is an operator whose precedence < the tempNode's token precedence

while (!myStack.isEmpty() &&

tempNode.getToken().getPrecedence() >= myStack.peek().getPrecedence())

{

resultQueue.offer(myStack.pop());

}

//after we are sure that the top operator precedence is less than the one we wanna add

//add (or push) it in the stack

myStack.push(tempNode.getToken());

}

//check if first char is the open paren

if (firstChar == '(')

//if yes, just add

myStack.push(tempNode.getToken());

//check if firstChar is the close paren

if (firstChar == ')')

{

//when we find a ')' in the input queue, it means that

//we should start shifting the tokens from stack to queue

//until we find a '(' in a stack that matches the queue, remove the '('

//here is when shifting is done, so whenever the '('

//is still in the stack and the stack is not empty

//KEEP POPPING AND OFFERING

while (myStack.peek().toString().charAt(0) != '('

&& !myStack.isEmpty())

{

resultQueue.offer(myStack.pop());

}

//When matching the '(' pop it from the stack

if (myStack.peek().toString().charAt(0) == '(')

{

myStack.pop();

}

}

}

//if we run thru the whole input queue, but stack is still not empty

while (!myStack.isEmpty()) {

resultQueue.offer(myStack.pop());

}

System.out.println(resultQueue.toString());

return resultQueue;

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!