-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfixtoPostfix.java
More file actions
83 lines (66 loc) · 2.04 KB
/
Copy pathInfixtoPostfix.java
File metadata and controls
83 lines (66 loc) · 2.04 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
import java.util.*;
public class InfixtoPostfix {
static int precedence(char ch) {
switch (ch) {
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
}
return -1;
}
static String infixToPostfix(String exp) {
StringBuilder result = new StringBuilder();
Stack<Character> stack = new Stack<>();
for (int i = 0; i < exp.length(); i++) {
char ch = exp.charAt(i);
if (ch == ' ')
continue;
if (Character.isDigit(ch)) {
while (i < exp.length() && Character.isDigit(exp.charAt(i))) {
result.append(exp.charAt(i));
i++;
}
result.append(" ");
i--;
}
else if (ch == '(') {
stack.push(ch);
}
else if (ch == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
result.append(stack.pop());
result.append(" ");
}
if (!stack.isEmpty())
stack.pop();
}
else {
while (!stack.isEmpty()
&& stack.peek() != '('
&& precedence(ch) <= precedence(stack.peek())) {
result.append(stack.pop());
result.append(" ");
}
stack.push(ch);
}
}
while (!stack.isEmpty()) {
result.append(stack.pop());
result.append(" ");
}
return result.toString().trim();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter infix expression: ");
String infix = sc.nextLine();
System.out.println("Postfix: " + infixToPostfix(infix));
sc.close();
}
}