What is a Linked List?
Before answer the question “How to implement Linked List in Java. Example.” we need to understand how it works. That is one of the basic types of data structures. The main principle here is connecting new elements to the end of the current element. It looks like a train. Where the train is the head of the Linked List, and the others are carriages. The end of each item, by default, ready to be connected. That’s why it is set to null.
Example of the implementation Linked List in Java.
There are two ways of creating the Linked List in Java.
First: By creating a LinkedList object, set the type of the item in the list, and after that, add some elements—the same steps as in regular ArrayList.
public void createLinkedList
{
// Creation of the object with type String
LinkedList<Integer> linkedList = new LinkedList<Integer>();
}
The second way to implement a linked list in java on an example model class. Without using existing LinkedList objects from Java collections. This way will help you understand the process of creating the Linked List in Java in more detail. Besides that, you might be asked for that in an interview.
First step:
We need to create a regular object that will be our node. Because that node will have two parts data and “tail.” We will need that “tail” to connect the current item to the next one. As a parameter, we will receive the data that we will store in the current node.
//Creation of the Linked list class
private static class ListNode {
private int data; // Head and data of the node
private ListNode next; // Reference to the next node. “Tail”
public ListNode(int data) {
// Setting data to the current object data field
this.data = data;
// Creating reference to the next node by default is null.
this.next = null;
}
}
Second step:
When the model class is done, we can create the Linked List in our implementation without calling Linked List from the collection.
public void creatingLinkedList() {
//In begin head = null
head = new ListNode(10);
//second node become 1
second = new ListNode(1);
//third node become 8
third = new ListNode(8);
//fourth node become 11
fourth = new ListNode(11);
//five node become 122
five = new ListNode(122);
//connecting head to second
head.next = second; // 10 --> 1
//connecting second to third
second.next = third; // 10 --> 1 --> 8
//connecting third to fourth
third.next = fourth; // 10 --> 1 --> 8 --> 11 --> null
//connecting four to five
fourth.next = five;
}
In this article, you figured out how to implement linked list in java on an example of two scenarios. With the help of the Java collections and in case of implementation via constructor and model class.
Useful links:
Leave Any Questions Related To This Article Below!