How to insert a node in Linked List at a given position in Java ?

By | June 18, 2020

In this post, we will learn How to insert a node in Linked List at a given position in Java?

Program Logic Explanation

Case 1: If the insertion position is zero(o) then assign head to newNode.next and newNode to head.

Case 2: If the insertion position >0 then

  1. We have to traverse the Linked list upto position-1 nodes.
  2. Once we traverse the position-1 nodes then allocate memory and the given data to the new node.
  3. Assign the next pointer of the new node to the next of the current node.
  4. Assign the next pointer of the current node to the new node.

Exception Handling:

Throw Exception if node insert position is less than zero.
Throw Exception if  node insertion position is greater than the number of nodes in the Linked List

Output of this program:

Original LinkedList:
10 20 30 40 50 60
Adding a Node with Value:80 at position:2
10 20 80 30 40 50 60

 You May Also Like:

That’s all about the How to insert a node in Linked List at a given position in Java?
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *