javaindexingmethodssingly-linked-listremove-method

SinglyLinkedList remove(int index) method


I have some problems when implementing a remove(int index) method that is supposed to remove an element at a specified index in a list. My first problem is how to shift any subsequent elements to the left and subtract one from their indices. I tried

Node.getmNextNode() = tempNode.getmNextNode().getmNextNode();

but it is not correct. My second problem is how to return the element previously at the specified index in the end.

public E remove(int index) throws IndexOutOfBoundsException {
    if (index < 0 || index >= size) {
        throw new IndexOutOfBoundsException();
    } else if (index == 0) {
        remove(0);
    } else {
        Node<E> tempNode = head;
        for  (int i = 0; i < index - 1; i++) {
            tempNode = tempNode.getmNextNode();
        }
        Node.getmNextNode() = tempNode.getmNextNode().getmNextNode();
        size--;
    }
    return ;
}

My Node class:

public class Node<E> {
private E mElement;
private Node<E> mNextNode;

Node(E data) {

    this.setmElement(data);
}
public E getmElement() {
    return this.mElement;
}
public void setmElement(E element) {
    this.mElement = element;
}
public Node<E> getmNextNode()
{
    return this.mNextNode;
}
public void setmNextNode(Node<E> node)
{
    this.mNextNode = node;
}}

Solution

  • You could try like this:

    tempNode.setmNextNode(tempNode.getmNextNode().getmNextNode());