简体   繁体   中英

Removing cursor from a doubly linked list

I am trying to remove the cursor from the list and make it reference to the previous CarListNode (or the head, if the cursor previously referenced the head of the list). While still returning the information inside the cursor. My code doesn't correctly remove the cursor. What is the issue in my code?

Here is my current code:

public Fruit removeCursor() throws EndOfListException {

    if (cursor == null) {
        throw new EndOfListException();

    } else if (cursor.getPrev() == null) {
        head = cursor.getNext();
        cursor.setNext(null);
        cursor.setPrev(null);
        cursor = head;

    } else if (cursor.getNext() == null) {
        tail = cursor.getPrev();
        cursor.setPrev(null);
        cursor.setNext(null);
        cursor = tail;

    } else {
        cursor.setData(cursor.getNext().getData()); //this isn't a singly linked list
        cursor.setNext(cursor.getNext().getNext());
    }

    count--;

    return cursor.getData();
}

Your else clause does not "remove the cursor"...

Try something like this:

else {
    cursor.getPrev().setNext(cursor.getNext());
    cursor.getNext().setPrev(cursor.getPrev());
    // You might want to release the cursor's item, EG:
    cursor = null;
    cursor = cursor.getNext();
}

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