addElementAt

This commit is contained in:
La Programmatrice Verde
2026-03-24 09:09:27 +01:00
parent f018d72b9c
commit 32816087fe

View File

@@ -1,9 +1,9 @@
package linkedlist; package linkedlist;
public class Lista<E> { public class Lista<E> {
Nodo<E> testa; Nodo<E> testa;
int size; int size = 0;
public Lista() { public Lista() {
this.testa = null; this.testa = null;
@@ -16,34 +16,55 @@ public class Lista<E> {
public void addFirst(E info) { public void addFirst(E info) {
if (this.testa == null) { if (this.testa == null) {
this.testa = new Nodo<>(info); this.testa = new Nodo<>(info);
} size++;
else { } else {
Nodo<E> nuovaTesta = new Nodo<>(info); Nodo<E> nuovaTesta = new Nodo<>(info);
nuovaTesta.setNext(this.testa); nuovaTesta.setNext(this.testa);
this.testa = nuovaTesta; this.testa = nuovaTesta;
size++;
} }
} }
public void addLast(E info) { public void addLast(E info) {
if (this.testa == null) { if (this.testa == null) {
addFirst(info); addFirst(info);
} } else {
else {
Nodo<E> nuovaCoda = new Nodo<>(info); Nodo<E> nuovaCoda = new Nodo<>(info);
Nodo<E> coda = this.testa; Nodo<E> coda = this.testa;
while (coda.getNext() != null) { while (coda.getNext() != null) {
coda = coda.getNext(); coda = coda.getNext();
} }
coda.setNext(nuovaCoda); coda.setNext(nuovaCoda);
size++;
} }
} }
//addLast(tipoInfo info): aggiunge un nodo in coda (es. tipoInfo = char, tipoInfo = int) public void addElementAt(E info, int posizione) throws IndexOutOfBoundsException {
//addElementAt(tipoInfo info, int pos): aggiunge un nodo nella posizione indicata da pos if (posizione == 0) {
//removeFirst(): rimuove il nodo in testa addFirst(info);
//removeLast(): rimuove il nodo in coda } else if (posizione == size - 1) {
//removeElementAt(int pos): rimuove il nodo in coda addLast(info);
//tipoInfo getElementAt(int pos): restituisce l'info presente nel nodo in posizione n (es. tipoInfo = char, tipoInfo = int) } else if (posizione < 0 || posizione >= size) {
//String toString() throw new IndexOutOfBoundsException();
} else {
Nodo<E> corrente = this.testa;
for (int i = 0; i < posizione; i++) {
corrente = corrente.getNext();
}
Nodo<E> nuovoNodo = new Nodo<>(info);
nuovoNodo.setNext(corrente.getNext());
corrente.setNext(nuovoNodo);
size++;
}
}
// addElementAt(tipoInfo info, int pos): aggiunge un nodo nella posizione
// indicata da pos
// removeFirst(): rimuove il nodo in testa
// removeLast(): rimuove il nodo in coda
// removeElementAt(int pos): rimuove il nodo in coda
// tipoInfo getElementAt(int pos): restituisce l'info presente nel nodo in
// posizione n (es. tipoInfo = char, tipoInfo = int)
// String toString()
} }