removeFirst

This commit is contained in:
La Programmatrice Verde
2026-03-24 09:15:20 +01:00
parent 32816087fe
commit 6948f80543

View File

@@ -1,5 +1,7 @@
package linkedlist; package linkedlist;
import java.util.NoSuchElementException;
public class Lista<E> { public class Lista<E> {
Nodo<E> testa; Nodo<E> testa;
@@ -41,7 +43,7 @@ public class Lista<E> {
} }
public void addElementAt(E info, int posizione) throws IndexOutOfBoundsException { public void addElementAt(E info, int posizione) throws IndexOutOfBoundsException {
if (posizione == 0) { if (posizione == 0 || this.testa == null) {
addFirst(info); addFirst(info);
} else if (posizione == size - 1) { } else if (posizione == size - 1) {
addLast(info); addLast(info);
@@ -59,8 +61,16 @@ public class Lista<E> {
} }
} }
// addElementAt(tipoInfo info, int pos): aggiunge un nodo nella posizione public E removeFirst() throws NoSuchElementException {
// indicata da pos if (this.testa != null) {
Nodo<E> testaVecchia = this.testa;
this.testa = this.testa.getNext();
return testaVecchia.getInfo();
} else {
throw new NoSuchElementException();
}
}
// removeFirst(): rimuove il nodo in testa // removeFirst(): rimuove il nodo in testa
// removeLast(): rimuove il nodo in coda // removeLast(): rimuove il nodo in coda
// removeElementAt(int pos): rimuove il nodo in coda // removeElementAt(int pos): rimuove il nodo in coda