When using Java LinkedList how do you find out the element's next or previous relationships?
I mean, in a regular linked list I would do something like this:
Node node1 = new Node(); Node node2 = new Node(); LinkedList list = new LinkedList(); list.add(node1); list.add(node2); //then my node1 will know who it's next is: assertEquals(node2, node1.next());
where Node is my own container for data/object.
But in Java's LinkedList, the data does not seem to be modified. So how do I actually find out who the "next" (or "previous" in the case of doubly-linked lists) element is?
LinkedList implements the Collection (and List) interface, so given an index i of an element in the list list , you can get previous and next elements with list. get(i-1) and list. get(i+1) , respectively.
getNext(); sets the value of second element of the LinkedList link into edgeLine , and then you loop and do the same, and then the same over and over and over again.
Create a LinkedList class and initialize the head node to null. Create the required add and search functions. Initialize the LinkedList in the main method. Use the search method to find the element.
LinkedList. indexOf(Object element) method is used to check and find the occurrence of a particular element in the list. If the element is present then the index of the first occurrence of the element is returned otherwise -1 is returned if the list does not contain the element.
You can't. LinkedList is just an implementation of List and offers about nothing more. You'd need to make your own.
For node1.next()
you'd need a reference from node1
to the List. Actually, you'd need multiple references, since node1
may be there multiple times. Moreover, it may be contained in multiple Lists.
Maybe you can use ListIterator
for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With