Home » Java » Java: Can anyone explain how node works in a linked list?-Exceptionshub

Java: Can anyone explain how node works in a linked list?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment


A linked list code contains

class Node{
int data;
Node next;
class l{
Node temp;

where temp.next is the node next to “temp”.
I understood the concept of the linked list but I am unable to understand how does it work inside java.
I cannot understand how can we even create a variable temp of the datatype “Node”. and how does temp.next point to the next node? how does it even work? Can anyone please explain?

How to&Answers:

Basically you are supposed to have nothing to do with the inner container class Node. And i suspect you are doing something wrong if you went into implementation but dont know how linked list works, so maybe you want to see a simple linked list tutotial for java. Here you can see some simple code examples.


If you want to implement your own collection(highly discouraged), I recommend to first understand how linked lists work; long story short, every element has reference to the next element in the list and container keeps only the first elements reference. This way when you need to collect them, you can iterate through these references and collect all your objects.

The first question you will face is how to keep reference of next object inside the given object? The solution is the class you asked, Node a simple container which keeps the object you want to keep and has reference to next and prev(optional) nodes. So you can put your object into a Node then put this Node into your Nodes chain, you will be able to implement the behavior we described. Again, these are all necessary if you are implementing your own linked list.

I’m not going to explain any further like how to add, remove or get elements as they are quite straight forward operations once you have the intuition about how they work. Here is a good material with pictures(data structures make no sense to me without pictures)!