diff --git a/src/linkedlist/Lista.java b/src/linkedlist/Lista.java index 468e7b4..78bd7fd 100644 --- a/src/linkedlist/Lista.java +++ b/src/linkedlist/Lista.java @@ -4,8 +4,8 @@ import java.util.NoSuchElementException; public class Lista { - Nodo testa; - int size = 0; + private Nodo testa; + private int size = 0; public Lista() { this.testa = null; @@ -18,12 +18,12 @@ public class Lista { public void addFirst(E info) { if (this.testa == null) { this.testa = new Nodo<>(info); - size++; + this.size++; } else { Nodo nuovaTesta = new Nodo<>(info); nuovaTesta.setNext(this.testa); this.testa = nuovaTesta; - size++; + this.size++; } } @@ -38,16 +38,16 @@ public class Lista { 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 corrente = this.testa; @@ -57,7 +57,7 @@ public class Lista { Nodo nuovoNodo = new Nodo<>(info); nuovoNodo.setNext(corrente.getNext()); corrente.setNext(nuovoNodo); - size++; + this.size++; } } @@ -65,13 +65,27 @@ public class Lista { if (this.testa != null) { Nodo 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 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