Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Node-Entry Reference from LinkedList in java

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.

like image 450
Dost Arora Avatar asked Mar 21 '26 18:03

Dost Arora


1 Answers

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)

like image 109
safir Avatar answered Mar 23 '26 07:03

safir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!