How to get Node-Entry Reference from LinkedList in java

Viewed 673

How to get the reference to the actual Node (entry) object from LinkedList - Not the value that it holds?
Something like this :

import java.util.LinkedList;

public class Main {

    public static void main(String[] args) {

        LinkedList<String> test = new LinkedList<String>();

        test.addLast("first");
        test.addLast("second");

        test.addLast("third");
        var thirdNodeReference = test.getLastNode(); // Does this even exist ?

        test.addLast("fourth");

        var secondNodeReference = thirdNodeReference.previous(); // To perform such operations.
    }

}

Does there exist a method like LinkedList.getLastNode() in java LinkedList so that one can perform previous() or next() operations on it?

I know LinkedList.listIterator() exists but that's not useful, because I'll be having references to each Node (entry), and I need to work with them - such as lastNodeReference in the code above.

If such a functionality doesn't exist in JAVA Standard Library, is there any 3rd party (external) Library that I can use?

Reason:

I need to access the Node to perform remove() operation in O(1).

In the actual JAVA code implementation it performs this in O(N) by traversing the list to find the Node containing the given object by performing equals() on every node on it's way. Also, check this comment.
This can be performed ideally in O(1) if we have a direct reference to Node object - because remove() only requires a change of 2 pointers of previous and next Node.

2 Answers

There is a descendingIterator method on LinkedList, which is described as Returns an iterator over the elements in this deque in reverse sequential order, while it isn't (completely) clear what OP wants, Iterator does have a .next, .previous, and .remove methods.

a linked list can be represented as such:
enter image description here

so no, you can't get the previous element with a linked list. You might want to implement a double linked list tho ( exemples codes can be found quite easily on google)

Related