Implementing Linked Lists with Java
An Overview of the Structure and Operations of a Linked List
Cover Photo by Bryson Hammer on Unsplash
I previously wrote an article on the basics of Linked Lists. If you haven’t read it, I advise you to go through it to understand the basics of Linked Lists.
As we now have a basic understanding of what Linked Lists are, let’s see how you can implement a linked list in Java.
Creating a Node
Let’s analyze the above-written code. We initially create a class called Node and provide it with two properties required by any node, as we learned at the beginning of this article. The integer variable called key is where the data is stored. For simplicity, we are only storing integers in our nodes. But keep in mind that you are free to use any data type. The next variable is of type Node. What this basically means is that it stores the memory location of an object type Node and thereby allowing you to access it.
Now we have successfully created the basic building block of a Linked List.
Creating a Linked List
That was simple, wasn’t it? We simply created a Linked List with a head Node and initialized it as null in the constructor. We also have a method to check whether the Linked List is empty. This method simply checks whether the head is null or not.
As we have created our very own Linked Lists, let’s see how we can perform basic operations given below on Linked Lists.
Basic Operations
Following are the basic operations supported by a linked list.
Insertion − Adds an element at the beginning of the linked list.
Deletion − Deletes an element from the linked list.
Search − Searches an element using the given key.
Insertion
We have to modify our Linked List class now.
Insertion can take place in three different ways.
Insertion at the beginning of the Linked List
Insertion at the end of the Linked List
Insertion after a given node
Insertion at the beginning of the Linked List
Insertion at the end of the Linked List
Insertion after a given node
Deletion
We can delete a node based on its position in the linked list. In order to succeed, we should traverse along with the linked list to our desired position and then delete the Node.
Search
We can search for a certain key in a linked list by traversing along with the nodes in a linked list.
Here is the full code for your reference.
That is all for this article. I hope you understood how to create a Linked List in Java.
Happy Coding!!