0
Given class No, being:
public class No<T> {
T elemento;
No<T> proximo;
No<T> anterior;
public No(T elemento, No<T> anterior, No<T> proximo) {
this.elemento = elemento;
this.proximo = proximo;
this.anterior = anterior;
}
public No(T elemento) {
this.elemento = elemento;
proximo = null;
anterior = null;
}
}
I must create a method boolean remover(T item)
, which I tried to do as follows:
public boolean remover(T item) {
if (primeiro.elemento.equals(item)) {
primeiro = primeiro.proximo;
primeiro.anterior = null;
return true;
}
No<T> n = primeiro;
T aux1 = null;
T aux2 = null;
while (n.proximo != null) {
if (item.equals(n.proximo.elemento)) {
aux1 = n.proximo.elemento;
n.proximo = n.proximo.proximo;
break;
}
n = n.proximo;
}
n = n.proximo;
while (n.anterior != null) {
if (item.equals(n.anterior.elemento)) {
aux2 = n.anterior.elemento;
n.anterior = n.anterior.anterior;
break;
}
n = n.anterior;
}
if (aux1 == aux2) {
tamanho--;
return true;
}
return false;
}
In this way, I was able to remove almost all items except the last one before the null
, when the program gives error.
There is something to be done to fix this or even a better construction for this method?
The program also gives
NullPointerException
if you try to remove an item from an empty list, correct?– Gabriel
Yeah, that’s right
– naosei
General case to remove an item from a double chained list: Find the node to be deleted and do the
proximo
of the former becoming theanterior
next. There are two special cases, which are the removal at the beginning or at the end of the list. To remove from the beginning, just makenull
theanterior
of the second element. To exclude from the end, simply makenull
theproximo
penultimate. If the list is empty, the methodremover
can be returned right at the beginning.– Gabriel
I don’t have access to Java at the moment, so I can’t create any code to help you or run your code. So I just explained in text only.
– Gabriel
All right, but if you can show me later, when you’re available, I’d appreciate it. It’s hard for me to visualize like this.
– naosei
Okay, if no one has answered by then, I’ll help you.
– Gabriel