Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ToPostfix{
- private Stack theStack;
- private String input;
- private Queue queue;
- public ToPostfix(String in){
- input = in;
- int stackSize = input.length();
- int queueSize = input.length();
- queue = new Queue(queueSize);
- theStack = new Stack(stackSize);
- }
- public String trabslation(){
- for(int j=0; j<input.length(); j++)
- {
- char ch = input.charAt(j);
- switch(ch)
- {
- case '+':
- case '-':
- operand(ch, 1);
- break;
- case '*':
- case '/':
- operand(ch, 2);
- break;
- case '(':
- theStack.push(ch);
- break;
- case ')':
- parent(ch);
- break;
- default:
- queue.enqueue(ch);
- break;
- }
- }
- while( !theStack.isEmpty()){
- queue.enqueue(theStack.pop());
- }
- return queue.getString();
- }
- public void operand(char opThis, int prec1){
- while( !theStack.isEmpty()){
- char opTop = theStack.pop();
- if( opTop == '(' ){
- theStack.push(opTop);
- break;
- }else{
- int prec2;
- if(opTop=='+' || opTop=='-')
- prec2 = 1;
- else
- prec2 = 2;
- if(prec2 < prec1){
- theStack.push(opTop);
- break;
- }
- else
- queue.enqueue(opTop);
- }
- }
- theStack.push(opThis);
- }
- public void parent(char ch){
- while( !theStack.isEmpty()){
- char chx = theStack.pop();
- if( chx == '(' )
- break;
- else
- queue.enqueue(chx);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment