Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package praktikum5;
- /*
- Infix: Bentuk yang udah kita ketahui -> 1 + 2 * (3 + 4)
- Postfix: Operand (bilangan) didahulukan -> 1 2 + 3 *
- Prefix: Kebalikan dari Postfix -> * 3 + 2 1
- */
- import java.util.Stack;
- public class InfixToPostfix {
- public static int urutan(char c) {
- if (c == '^') return 3;
- if (c == '*' || c == '/') return 2;
- if (c == '+' || c == '-') return 1;
- return 0;
- }
- public static void main(String[] args) {
- String input = "1+2*(3+4)";
- char[] persamaan = input.toCharArray();
- String hasil = "";
- Stack<Character> stack = new Stack<>();
- // 1. Jika char berupa angka, langsung push ke hasil akhir
- // 2. Jika char berupa (, langsung push ke stack
- // 3. Jika char berupa ), keluarin semua isi stack sampai ketemu (
- // 4. Jika char berupa operator, maka:
- // keluarin semua isi stack sampai ketemu operator yang urutannya lebih tinggi
- // Jika sudah selesai, maka: Keluarkan semua isi stack sampai habis
- for (int i = 0; i < persamaan.length; i++) {
- char c = persamaan[i];
- if (Character.isDigit(c)) {
- hasil += c;
- }
- else if (c == '(') {
- stack.push(c);
- }
- else if (c == ')') {
- while (true) {
- char s = stack.pop();
- if (s == '(') break;
- else hasil += s;
- }
- }
- else {
- while (!stack.isEmpty() && urutan(c) <= urutan(stack.peek())) {
- hasil += stack.pop();
- }
- stack.push(c);
- }
- }
- while (!stack.isEmpty()) {
- hasil += stack.pop();
- }
- System.out.println(hasil);
- }
- }
Add Comment
Please, Sign In to add comment