removeLast

This commit is contained in:
La Programmatrice Verde
2026-03-24 09:23:19 +01:00
parent 6948f80543
commit 76fbd74556

View File

@@ -4,8 +4,8 @@ import java.util.NoSuchElementException;
public class Lista<E> {
Nodo<E> testa;
int size = 0;
private Nodo<E> testa;
private int size = 0;
public Lista() {
this.testa = null;
@@ -18,12 +18,12 @@ public class Lista<E> {
public void addFirst(E info) {
if (this.testa == null) {
this.testa = new Nodo<>(info);
size++;
this.size++;
} else {
Nodo<E> nuovaTesta = new Nodo<>(info);
nuovaTesta.setNext(this.testa);
this.testa = nuovaTesta;
size++;
this.size++;
}
}
@@ -38,16 +38,16 @@ public class Lista<E> {
coda = coda.getNext();
}
coda.setNext(nuovaCoda);
size++;
this.size++;
}
}
public void addElementAt(E info, int posizione) throws IndexOutOfBoundsException {
if (posizione == 0 || this.testa == null) {
addFirst(info);
} else if (posizione == size - 1) {
} else if (posizione == this.size - 1) {
addLast(info);
} else if (posizione < 0 || posizione >= size) {
} else if (posizione < 0 || posizione >= this.size) {
throw new IndexOutOfBoundsException();
} else {
Nodo<E> corrente = this.testa;
@@ -57,7 +57,7 @@ public class Lista<E> {
Nodo<E> nuovoNodo = new Nodo<>(info);
nuovoNodo.setNext(corrente.getNext());
corrente.setNext(nuovoNodo);
size++;
this.size++;
}
}
@@ -65,13 +65,27 @@ public class Lista<E> {
if (this.testa != null) {
Nodo<E> testaVecchia = this.testa;
this.testa = this.testa.getNext();
this.size--;
return testaVecchia.getInfo();
} else {
throw new NoSuchElementException();
}
}
// removeFirst(): rimuove il nodo in testa
public E removeLast() throws NoSuchElementException {
if (this.testa != null) {
Nodo<E> codaNuova = this.testa;
for (int i = 0; i < this.size - 2; i++) {
codaNuova = codaNuova.getNext();
}
E ultimo = codaNuova.getNext().getInfo();
codaNuova.setNext(null);
return ultimo;
} else {
throw new NoSuchElementException();
}
}
// 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