-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathinfixToPrefix.java
More file actions
92 lines (82 loc) · 3.22 KB
/
Copy pathinfixToPrefix.java
File metadata and controls
92 lines (82 loc) · 3.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Java Program to convert an Infix Expression to a Prefix Expression using Stack.
/*
An infix expression is basically the algebraic expression which we write normally. On the other hand, a prefix expression is a special
way of representing an infix expression, where after each operation, the operator is written before the operands.
For example,
Suppose the infix operation is A+B*(C/D + E) - F
The prefix of the expression becomes +A-*B+/CDEF
*/
import java.util.*;
public class infixToPrefix {
private static boolean isOperator(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
private static int getPrecedence(char op) {
/*
* This method returns the precedence of the operator.
* Arguments: char
* Return type: int
*/
switch (op) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
}
return 0;
}
public static String infixToPrefix(String infix) {
/*
* This method converts the infix expression to prefix expresison, by utilising
* stacks.
* Arguments: String
* Return type: String
*/
Stack<Character> stack_operator = new Stack<>();
Stack<String> stack_operand = new Stack<>();
for (int i = infix.length() - 1; i >= 0; i--) {
char ch = infix.charAt(i);
if (Character.isLetterOrDigit(ch)) {
stack_operand.push(Character.toString(ch));
} else if (ch == ')') {
stack_operator.push(ch);
} else if (ch == '(') {
while (!stack_operator.isEmpty() && stack_operator.peek() != ')') {
char op = stack_operator.pop();
String o1 = stack_operand.pop();
String o2 = stack_operand.pop();
String temp = op + o1 + o2;
stack_operand.push(temp);
}
stack_operator.pop();
} else if (isOperator(ch)) {
while (!stack_operator.isEmpty() && getPrecedence(stack_operator.peek()) >= getPrecedence(ch)) {
char op = stack_operator.pop();
String o1 = stack_operand.pop();
String o2 = stack_operand.pop();
String temp = op + o1 + o2;
stack_operand.push(temp);
}
stack_operator.push(ch);
}
}
while (!stack_operator.isEmpty()) {
char op = stack_operator.pop();
String o1 = stack_operand.pop();
String o2 = stack_operand.pop();
String temp = op + o1 + o2;
stack_operand.push(temp);
}
return stack_operand.pop();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter an infix expression: ");
String infixExpression = sc.nextLine();
String prefixExpression = infixToPrefix(infixExpression);
System.out.println("Infix Expression: " + infixExpression);
System.out.println("Prefix Expression: " + prefixExpression);
}
}