How to implement a Linked List in Java, top 3 operations

You just got an understanding of the basic concepts of Linked List and their variance. Now it’s time to implement a Linked List in Java to dive into the common Linked List operations that can be performed. Before you implement a Linked List in Java we remind you two important things about linked list:

  • head points to the first node of the linked list.
  • next pointer of last node is NULL.

Implement a Linked List in Java

Simple Linked List

In this post, you will implement a linked list in java with three nodes. The simple linked list is designed like below

How to traverse a linked list

It’s easy to traverse a linked list. You know that next points of last node is NULL. So you keep moving the next node when next points to NULL then you have reached the end of linked list.

Here is output of the above program

How to insert a node to linked list

In this post, methods to insert a new node in linked list are discussed. A node can be added in three ways:

  1. At the front of the linked list.
  2. After a given node.
  3. At the end of the linked list.
At the front of the linked list

Time complexity of push() is O(1) as it does constant amount of work.

Add a node after a given node

Time complexity of insertAfter() is O(1) too.

Add a node at the end

Here, you add a new node after the last node of linked list. You must traverse the list till end then change the next node of the last node to new node. So, time complexity of append is O(n) where n is the number of nodes in linked list.

Delete a node at a given position

Completely implement a linked list in Java

Here is a simple program which implement a linked list in Java and its top 3 operations(traverse, add, delete)

Here is output of the above program that implement a Linked List in Java

How to implement a Linked List in Java

That’s all about the tutorial how to implement a Linked List in Java.

References

Linked List Data Structure in Java
Data Structures and Algorithms Tutorial in Java

Please share it if you found this useful
Hide Buttons