-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedLists-listasEnlazadas.js
More file actions
111 lines (89 loc) · 2.34 KB
/
linkedLists-listasEnlazadas.js
File metadata and controls
111 lines (89 loc) · 2.34 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Clase Nodo (Node)
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Clase ListaEnlazada (LinkedList)
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
// Método agregar (add): agrega un nuevo nodo al final de la lista
add(data) {
const newNode = new Node(data);
if (this.head === null) {
this.head = newNode;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
this.size++;
}
// Método eliminar (remove): elimina el nodo con el dato especificado
remove(data) {
if (this.head === null) {
return null;
}
if (this.head.data === data) {
this.head = this.head.next;
} else {
let current = this.head;
let previous = null;
while (current !== null && current.data !== data) {
previous = current;
current = current.next;
}
if (current === null) {
return null;
}
previous.next = current.next;
}
this.size--;
}
// Método buscar (find): busca un nodo con el dato especificado
find(data) {
let current = this.head;
while (current !== null) {
if (current.data === data) {
return current;
}
current = current.next;
}
return null;
}
// Método isEmpty: verifica si la lista está vacía
isEmpty() {
return this.size === 0;
}
// Método size: retorna el número de nodos en la lista
getSize() {
return this.size;
}
// Método imprimir (print): imprime los datos de los nodos de la lista
print() {
let current = this.head;
const elements = [];
while (current !== null) {
elements.push(current.data);
current = current.next;
}
console.log(elements.join(" -> "));
}
}
// Ejemplo de uso de la clase ListaEnlazada (LinkedList)
const list = new LinkedList();
list.add(1); // Agrega 1 a la lista
list.add(2); // Agrega 2 a la lista
list.add(3); // Agrega 3 a la lista
list.print(); // Imprime: 1 -> 2 -> 3
console.log(list.find(2)); // Retorna el nodo con el dato 2
console.log(list.getSize()); // Retorna el tamaño de la lista: 3
console.log(list.isEmpty()); // Verifica si la lista está vacía: false
list.remove(2); // Elimina el nodo con el dato 2
list.print(); // Imprime: 1 -> 3