addElementAt

This commit is contained in:
La Programmatrice Verde
2026-03-24 09:09:27 +01:00
parent f018d72b9c
commit 32816087fe

View File

@@ -3,7 +3,7 @@ package linkedlist;
public class Lista<E> {
Nodo<E> testa;
int size;
int size = 0;
public Lista() {
this.testa = null;
@@ -16,19 +16,19 @@ public class Lista<E> {
public void addFirst(E info) {
if (this.testa == null) {
this.testa = new Nodo<>(info);
}
else {
size++;
} else {
Nodo<E> 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<E> nuovaCoda = new Nodo<>(info);
Nodo<E> coda = this.testa;
@@ -36,14 +36,35 @@ public class Lista<E> {
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
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<E> corrente = this.testa;
for (int i = 0; i < posizione; i++) {
corrente = corrente.getNext();
}
Nodo<E> 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)
// tipoInfo getElementAt(int pos): restituisce l'info presente nel nodo in
// posizione n (es. tipoInfo = char, tipoInfo = int)
// String toString()
}