Question: I need to create a infix to prefix program. I am not allowed to convert to postfix and then to prefix. Here is the code
I need to create a infix to prefix program. I am not allowed to convert to postfix and then to prefix. Here is the code I have done so far, I just need help polishing and fixing the program.
public class Stack { private final char STACKSIZE = 100; private char top; private char[] items; // TO DO: implement the stack methods, see slides and/or book public Stack(){ items = new char[STACKSIZE]; } public boolean empty(){ // check if stack is empty if(top == -1) return true; else { return false; } } public char pop(){ // check if stack is empty if(empty()){ System.out.println("Stack Underflow"); System.exit(1); } return items[top--]; } // end pop public void push(char x) { // check if stack is full if(top == STACKSIZE - 1){ System.out.println("Stack Overflow"); System.exit(1); } items[++top] = x; } // end push public char peek(){ // check if stack is empty if(empty()){ System.out.println("Stack Underflow"); System.exit(1); } return items[top]; } // end peek } class prefix { public static boolean isOperand(char symb) { if (symb == '+' || symb == '-' || symb == '*' || symb == '/' || symb == '$' || symb == '(' || symb == ')') { return true; } else { return false; } } public static String infix_to_prefix(String infix) { // TO DO: implement this method to convert and return // the prefix of the infix string // you should call the precedence() method Stack opstk = new Stack(); // initialize stack String prefix = ""; char symbol; for (int position = infix.length() - 1; position > 0; position--) { symbol = infix.charAt(position); if (isOperand(symbol)) { prefix = prefix + symbol + " "; } else if (symbol == '(') { prefix = ((Character) opstk.pop()).toString() + prefix; } else if (symbol == ')') { } else { opstk.push(symbol); } } return prefix; } public static int precedence(char op) { // TO DO: complete this method to compare for precedence // op2 is the operator on top of stack, op1 is the incoming operator /* opcode for + or - is 1*/ /* opcode for * or / is 2 */ /* opcode for $ is 3 */ if (op == '+' || op == '-') return 1; else if (op == '*' || op == '/') return 2; else if (op == '$') return 3; else return 0; } } Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
