Question

Im trying to create a public bool remove(E element) method that removes the first node that includes the element and if no such a node is found it returns false otherwise true...How can I do that ? im having trouble linking the removed node's predecessor to its successor to close the gap created by the node's removal...this is my code so far...thank you

public class SinglyLinkedList<E> {
private final SLNode<E> head;
private final SLNode<E> tail;
int length;

// creates an empty list
public SinglyLinkedList() {
    head = new SLNode<E>();
    tail = new SLNode<E>();
    head.setSuccessor(tail);
    length = 0;
}

// adds new node on beginning of the list
public void add(E element) {
    SLNode<E> node = new SLNode<E>(element, null);
    node.setSuccessor(head.getSuccessor());
    head.setSuccessor(node);
}

// adds new node on beginning of the list
public void add(SLNode<E> node) {
    node.setSuccessor(head.getSuccessor());
    head.setSuccessor(node);
}

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    SLNode<E> cursor = head.getSuccessor();
    while (cursor != tail) {
        sb.append(cursor.getElement()).append(" ");
        cursor = cursor.getSuccessor();
    }
    sb.append("\n");
    return sb.toString();
}
 }

slnode class

public class SLNode<E> {
private E element;
private SLNode<E> successor;

public SLNode() {
    element = null;
    successor = null;
}

public SLNode(E theElement, SLNode<E> theSuccessor) {
    element = theElement;
    successor = theSuccessor;
}

public E getElement() {
    return element;
}

public void setElement(E newElement) {
    element = newElement;
}

public SLNode<E> getSuccessor() {
    return successor;
}

public void setSuccessor(SLNode<E> newSuccessor) {
    successor = newSuccessor;
}
  }
Was it helpful?

Solution

The trick is as you iterate, you need to keep a reference to both the previous and the current element. The reference to the previous element is what lets you close the gap:

public boolean remove(E element) {
    SLNode<E> previous = head;
    SLNode<E> current = head.getSuccessor();

    while (current != tail) {
        if (current.getElement().equals(element)) {
            previous.setSuccessor(current.getSuccessor());

            return true;
        }

        previous = current;
        current = current.getSuccessor();
    }

    return false;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top