From 32816087fe6e42b9528a74429447e2536aa87110 Mon Sep 17 00:00:00 2001 From: La Programmatrice Verde Date: Tue, 24 Mar 2026 09:09:27 +0100 Subject: [PATCH] addElementAt --- src/linkedlist/Lista.java | 49 ++++++++++++++++++++++++++++----------- 1 file changed, 35 insertions(+), 14 deletions(-) diff --git a/src/linkedlist/Lista.java b/src/linkedlist/Lista.java index 39b3471..9055059 100644 --- a/src/linkedlist/Lista.java +++ b/src/linkedlist/Lista.java @@ -1,9 +1,9 @@ package linkedlist; public class Lista { - + Nodo testa; - int size; + int size = 0; public Lista() { this.testa = null; @@ -16,34 +16,55 @@ public class Lista { public void addFirst(E info) { if (this.testa == null) { this.testa = new Nodo<>(info); - } - else { + size++; + } else { Nodo nuovaTesta = new Nodo<>(info); nuovaTesta.setNext(this.testa); this.testa = nuovaTesta; + size++; } } public void addLast(E info) { if (this.testa == null) { addFirst(info); - } - else { + } else { Nodo nuovaCoda = new Nodo<>(info); - + Nodo coda = this.testa; while (coda.getNext() != null) { coda = coda.getNext(); } coda.setNext(nuovaCoda); + size++; } } -//addLast(tipoInfo info): aggiunge un nodo in coda (es. tipoInfo = char, tipoInfo = int) -//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() + public void addElementAt(E info, int posizione) throws IndexOutOfBoundsException { + if (posizione == 0) { + addFirst(info); + } else if (posizione == size - 1) { + addLast(info); + } else if (posizione < 0 || posizione >= size) { + throw new IndexOutOfBoundsException(); + } else { + Nodo corrente = this.testa; + for (int i = 0; i < posizione; i++) { + corrente = corrente.getNext(); + } + Nodo 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() }