Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class infix_to_postfix {
- public infix_to_postfix(){}
- static int prioridade(char token){
- switch(token){
- case '+':
- case '-':
- return 1;
- case '*':
- case '/':
- return 2;
- }
- return 0;
- }
- public String infix_to_postfix(String[] infix){
- Stack <Character> stack = new Stack();
- String postfix = "";
- char c;
- String current = "";
- for (int i = 0; i < infix.length; i++){
- current = infix[i];
- c = current.charAt(0);
- //is number
- if (c >= '0' && c <= '9'){
- postfix += current;
- postfix += " ";
- }
- else if (stack.isEmpty() || (stack.top() == '(')){
- stack.push(c);
- }
- else if (c == '('){
- stack.push(c);
- }
- else if (c == ')'){
- while (c !='('){
- postfix += stack.pop();
- i++;
- current = infix[i];
- }
- stack.pop();
- }
- else if ((c == '*' || c == '/') && (!stack.isEmpty() || stack.top() == '+' || stack.top() == '-')){
- stack.push(c);
- }
- else if (c == stack.top()){
- postfix += stack.pop() + " ";
- stack.push(c);
- }
- else if ((c == '+' || c == '-') && (!stack.isEmpty() || stack.top() == '*' || stack.top() == '/')){
- while (!stack.isEmpty() && (stack.top() != '+' || stack.top() != '-')){
- postfix += stack.pop() + " ";
- }
- //postfix += stack.pop() + " ";
- stack.push(c);
- }
- }
- while (!stack.isEmpty()){
- postfix += stack.pop() + " ";
- }
- return postfix;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement