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.