Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Write a description of class infixtopostfix here.
- *
- * @author Samuel Berkat Hulu
- * @version 5.0 21-April-2021
- */
- public class infixtopostfix
- {
- private Stack theStack;
- private String input;
- private Queue queue;
- public infixtopostfix(String in)
- {
- input = in;
- int stackSize = input.length();
- int queueSize = input.length();
- queue = new Queue(queueSize);
- theStack = new Stack(stackSize);
- }
- //Lakukan terjemahan ke postfix
- public String doTrans()
- {
- for(int j=0; j<input.length(); j++)
- {
- char ch = input.charAt(j);
- switch(ch)
- {
- case '+':
- case '-':
- gotOper(ch, 1);
- break;
- case '*':
- case '/':
- gotOper(ch, 2);
- break;
- case '(':
- theStack.push(ch);
- break;
- case ')':
- gotParen(ch);
- break;
- default:
- queue.enqueue(ch);
- break;
- }
- }
- while( !theStack.isEmpty() )
- {
- queue.enqueue(theStack.pop());
- }
- return queue.getString();
- }
- public void gotOper(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 gotParen(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
Advertisement