Pregunta

I'm not sure if this is a proper way of creating a remove method for my circular list, also I'm having a problem with getting it to work for a 1 Node list.

public void remove() {
    if(first.getNext() == null) {
        first = null;
        first.setNext(null);
    } else {
        Node current = first;
        for(int i = 0; i < getSize() - 1; i++) {
            current = current.getNext();
        }
        first = first.getNext();
        current.setNext(first);
        size--;
    }
}

I have it working properly for lists that are greater than two, but I am not sure if this was the best way to tackle the problem. Does anyone have any suggestions for ways to improve this, as well as getting a one Node list to remove properly? Even though I set the first node to null, and the next Node to null as well, it still returns back my original input.

EDIT: For anyone who looks at this in the future, I just printed out a message saying that you cannot remove the element. As my assignment was quite ambiguous with what to do for it.

¿Fue útil?

Solución

This can not work. I guess, it does not get to execute the follwoing part at all:

    first = null;
    first.setNext(null);

The reason i sthat this would raise a NullpointerException. You first set the firstto null and than try to dereference the null.

I will not provide you the exact code (as this is some kind of homework right? ;)), but check this pseudo code from wikipedia (http://en.wikipedia.org/wiki/Doubly_linked_list):

  function remove(List list, Node node)
    if node.prev == null
      list.firstNode := node.next
    else
      node.prev.next := node.next
    if node.next == null
      list.lastNode := node.prev
    else
      node.next.prev := node.prev
    destroy node
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top