forked from Rodlemus03/HT4-2.0
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStacksVectores.java
More file actions
56 lines (51 loc) · 1.73 KB
/
StacksVectores.java
File metadata and controls
56 lines (51 loc) · 1.73 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
import java.util.*;
public class StacksVectores {
// Función para obtener la precedencia de los operadores
static int jerarquia(char car) {
switch (car) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default:
return -1;
}
}
static String convertir(String ex){
String expresion= ex.replace(" ","");
String nueva = "";
char[] vector = new char[expresion.length()];
int posicion = 0;
stacks stack=new stacks();
for (int i = 0; i < expresion.length(); i++) {
char ch = expresion.charAt(i);
if (Character.isLetterOrDigit(ch)) {
vector[posicion++] = ch;
} else if (ch == '(') {
stack.push(String.valueOf(ch));
} else if (ch == ')') {
while (!stack.empty() && stack.peek() != "(")
vector[posicion++] = stack.pop().charAt(0);
if (!stack.empty() && stack.peek() != "(")
return "Expresión inválida";
else
stack.pop();
} else {
while (!stack.empty() && jerarquia(ch) <= jerarquia(stack.peek().charAt(0)))
vector[posicion++] = stack.pop().charAt(0);
stack.push(String.valueOf(ch));
}
}
while (!stack.empty())
vector[posicion++] = stack.pop().charAt(0);
int pivote=0;
return new String(vector, pivote, posicion);
}
public static void main(String[] args) {
System.out.println(convertir("5+5"));
}
}