简体   繁体   中英

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;
}}

你可以这样尝试:

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

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;
}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM