From 34a3602b0dba54f831d45d3d8154df658d9499cd Mon Sep 17 00:00:00 2001 From: La Programmatrice Verde Date: Tue, 24 Mar 2026 09:33:50 +0100 Subject: [PATCH] getElementAt --- src/linkedlist/Lista.java | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/linkedlist/Lista.java b/src/linkedlist/Lista.java index 6670e56..3cf784a 100644 --- a/src/linkedlist/Lista.java +++ b/src/linkedlist/Lista.java @@ -106,7 +106,30 @@ public class Lista { } } - // removeElementAt(int pos): rimuove il nodo in coda + public E getElementAt(int posizione) throws IndexOutOfBoundsException, NoSuchElementException { + if (posizione == 0) { + if (this.testa == null) { + throw new NoSuchElementException(); + } else { + return this.testa.getInfo(); + } + } else if (posizione == this.size - 1) { + Nodo coda = this.testa; + while (coda.getNext() != null) { + coda = coda.getNext(); + } + return coda.getInfo(); + } else if (posizione < 0 || posizione >= this.size) { + throw new IndexOutOfBoundsException(); + } else { + Nodo corrente = this.testa; + for (int i = 0; i < posizione; i++) { + corrente = corrente.getNext(); + } + return corrente.getInfo(); + } + } + // tipoInfo getElementAt(int pos): restituisce l'info presente nel nodo in // posizione n (es. tipoInfo = char, tipoInfo = int) // String toString()