[java] prefixtoinfix
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
- import java.util.NoSuchElementException;
- import java.util.Scanner;
- public class PrefixToInfix {
- public static boolean isOperator(char c) {
- return c == '+' || c == '-' || c == '*' || c == '/';
- }
- public static String convertPrefixToInfix(String prefix) {
- StringDoubleEndedQueueImpl<String> queue = new StringDoubleEndedQueueImpl<>();
- char[] prefixCharArray = prefix.toCharArray();
- int N = prefixCharArray.length;
- for (int i = 0; i < N; i++) {
- if (Character.isDigit(prefixCharArray[i])) {
- queue.addFirst(String.valueOf(prefixCharArray[i]));
- } else if (isOperator(prefixCharArray[i])) {
- String item1 = queue.getLast();
- queue.removeLast();
- String item2 = queue.getLast();
- queue.removeLast();
- queue.addLast("(" + item2 + prefixCharArray[i] + item1 + ")");
- } else {
- throw new NoSuchElementException();
- }
- }
- return queue.getLast();
- }
- public static String convertPrefixToPostfix(String prefix) {
- StringDoubleEndedQueueImpl<String> queue = new StringDoubleEndedQueueImpl<>();
- char[] prefixCharArray = prefix.toCharArray();
- int N = prefixCharArray.length;
- for (int i = N - 1; i >= 0; i--) {
- if (Character.isDigit(prefixCharArray[i])) {
- queue.addFirst(String.valueOf(prefixCharArray[i]));
- } else if (isOperator(prefixCharArray[i])) {
- String item1 = queue.getFirst();
- queue.removeFirst();
- String item2 = queue.getFirst();
- queue.removeFirst();
- queue.addFirst(item1 + item2 + prefixCharArray[i]);
- } else {
- throw new NoSuchElementException();
- }
- }
- return queue.getFirst();
- }
- public static void main(String[] args) {
- Scanner myObj = new Scanner(System.in);
- System.out.println("Enter prefix: ");
- String prefix = myObj.nextLine();
- // Convert prefix to infix
- String infixExpression = convertPrefixToInfix(prefix);
- System.out.println("Infix Expression: " + infixExpression);
- myObj.close();
- }
- }
Editor
You can edit this paste and save as new: