This article describes the Java data structure and the method in which the prefix expression of the algorithm is converted to a suffix expression. Share to everyone for your reference, specific as follows:
Stack public class Stackx {private int top;
Private char[] Stackarray;
private int maxSize;
Constructor public Stackx (int maxSize) {this.maxsize = maxSize;
This.top =-1;
Stackarray = new Char[this.maxsize];
}//put item on top stack public void push (char push) {stackarray[++top] = push;
}//take item from top to stack public char pop () {return stackarray[top--];
}//peek the top item from stack public char peek () {return stackarray[top];
}//peek the character at index N public char peekn (int index) {return stackarray[index];
//true if stack is empty public boolean isempty () {return (top = 1);
//return stack size public int size () {return top+1;
}//intopost public class Intopost {private Stackx mystack;
private String input;
Private String output= "";
Constructor public intopost (String input) {this.input = input;
Mystack = new Stackx (This.input.length ()); }//do Translation to PostFix public String DoTrans () {for (int i=0; i<input.length (); i++) {Char ch = Input.char
at (i);
Switch (CH) {case ' + ': Case '-': This.getoper (ch,1);
Break
Case ' * ': Case '/': This.getoper (ch,2);
Break
Case ' (': This.getoper (CH, 3);
Break
Case ') ': This.getoper (CH, 4);
Break
Default:this.outPut = this.output + ch;
} while (!this.mystack.isempty ()) {this.output = This.output + This.myStack.pop ();
return this.output;
}//get operator from input public void getoper (char ch, int prect1) {char temp; if (This.myStack.isEmpty () | |
prect1==3) {this.myStack.push (CH);
else if (prect1==4) {while (!this.mystack.isempty ()) {temp = This.myStack.pop ();
if (temp== ') continue;
This.output = this.output + temp; } else if (prect1==1) {temp = this. Mystack.peek ();
if (temp== ') This.myStack.push (CH);
else{this.output = this.output + This.myStack.pop ();
This.myStack.push (CH);
} else{temp = This.myStack.peek (); if (temp==) (' | | temp== ' + ' | |
temp== '-') This.myStack.push (CH);
else{this.output = this.output + This.myStack.pop ();
}}}//test public class Testintopost {private static intopost intopost;
private static String str;
public static void Main (String []args) {str = "((a+b) *c)-D";
Intopost = new Intopost (str);
System.out.println (Intopost.dotrans ());
}
}
PS: The implementation of the algorithm is not very perfect, some complex expression parsing to make mistakes, write to do a souvenir!
More about Java algorithms Interested readers can view the site topics: "Java data structure and algorithms tutorial", "Java Operation DOM node skills summary", "Java file and directory operation tips Summary" and "Java Cache operation Tips"
I hope this article will help you with Java programming.