We know that the LinkedList class in Java is a doubly-linked list implementation of the List interface. This post provides an overview of common techniques to implement a linked list in Java programming language.

 
We know that each node of a linked list contains a single data field and a reference to the next node in the list. The nodes of the linked list are allocated in the heap memory during runtime by the JVM. We can use the constructor of the Node class to initialize the data field and the next pointer.

Practice this problem

 
There are several methods to construct a singly linked list in Java:

1. Naive method

A simple solution would be to allocate memory for all individual nodes of the linked list, set their data, and rearrange their references to build the complete list.

Linked List Implementation

Download  Run Code

 
We can write the above code in a single line by passing the next node as an argument to the Node constructor:

Download  Run Code

2. Return Head Node

The standard solution adds a single node to the head end of any list. This function is called push() since we are adding the link to the head end, making a list look a bit like a stack.

Linked List Construction

 
This is demonstrated below, where we return the head node from the push() function and update the head in the caller.

Download  Run Code

3. Make head reference global

We can construct a linked list by making the head reference global, but this approach is not recommended since global variables are usually considered bad practice.

Download  Run Code

 
Continue Reading:

Linked List – Insertion at Tail | C, Java, and Python Implementation

 
Also See:

Linked List Implementation in C

Linked List Implementation in C++

Linked List Implementation in Python

 
References: http://cslibrary.stanford.edu/103/LinkedListBasics.pdf