-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStacksListasDobles.java
More file actions
61 lines (49 loc) · 1.82 KB
/
StacksListasDobles.java
File metadata and controls
61 lines (49 loc) · 1.82 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
import java.util.*;
public class StacksListasDobles {
public static int jerarquia(char ch) {
switch (ch) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default:
return -1;
}
}
public static String convertir(String infix) {
StringBuilder postfix = new StringBuilder();
LinkedList stack = new LinkedList();
for (int i = 0; i < infix.length(); i++) {
char ch = infix.charAt(i);
// Si es un operando, agregar al resultado
if (Character.isLetterOrDigit(ch)) {
postfix.append(ch);
}
// Si es un paréntesis izquierdo, agregar a la lista
else if (ch == '(') {
stack.addLast(ch);
}
// Si es un paréntesis derecho, desenlazar todos los operadores
// hasta encontrar el paréntesis izquierdo correspondiente
else if (ch == ')') {
while (!stack.isEmpty() && stack.tail.data != '(') {
postfix.append(stack.removeLast());
}
if (!stack.isEmpty() && stack.tail.data != '(') {
return "Expresión inválida";
} else {
stack.removeLast();
}
}
// Si es un operador, desenlazar operadores con mayor o igual precedencia
// y agregarlos al resultado antes de agregar el operador actual a la lista
else {
while (!stack.isEmpty() && getPrecedence(ch) <= getPrecedence(stack.tail.data));
}
}
}
}