Last active
November 3, 2019 20:47
-
-
Save melvincabatuan/544f08b6821cd7a877d4799f13db136c to your computer and use it in GitHub Desktop.
simple infix2postfix conversion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
public class Main | |
{ | |
static String infix2postfix(String input) | |
{ | |
Stack<Character> temp_s = new Stack<>(); | |
String result=""; | |
for(int i = 0; i < input.length(); ++i) | |
{ | |
if(isOperand(input.charAt(i))) | |
result += input.charAt(i); | |
else if (input.charAt(i) == '(') | |
temp_s.push('('); | |
else if(input.charAt(i) == ')') | |
{ | |
while(!temp_s.empty() && temp_s.peek() != '(') | |
{ | |
result += temp_s.pop(); | |
} | |
if(temp_s.peek() == '(') | |
{ | |
temp_s.pop(); | |
} | |
} | |
else { | |
while(!temp_s.empty() && priority(input.charAt(i)) <= priority(temp_s.peek())) | |
{ | |
result += temp_s.pop(); | |
} | |
temp_s.push(input.charAt(i)); | |
} | |
} | |
while(!temp_s.empty()) | |
{ | |
result += temp_s.pop(); | |
} | |
return result; | |
} | |
static int priority(char c) | |
{ | |
if(c == '¬') return 5; | |
else if(c == '∧') return 4; | |
else if(c == '∨') return 3; | |
else if(c == '→') return 2; | |
else if(c == '↔') return 1; | |
else return -1; | |
} | |
static boolean isOperand(char c){ | |
return ((c >= 'a' && c <= 'z')||(c >= 'A' && c <= 'Z')); | |
} | |
public static void main(String[] args) { | |
System.out.println(infix2postfix("p∨q∧¬p∨r→q∨r")); // out: pqp¬∧∨r∨qr∨→ | |
System.out.println(infix2postfix("((p∨q)∧(¬p∨r))→(q∨r)")); // out:pq∨p¬r∨∧qr∨→ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment