How to find middle node in a Singly Linked List in Java ?

By | June 18, 2020

In this post, We will learn How to find the middle node in a Singly Linked List in Java?

When We talk about finding the middle node of Linked List then we have the following two cases:

NOTE: Here our intension is to find a middle element of LinkedList in Single pass.

CASE 1: When Linked List has an even number of nodes

Case 2:When Linked List has an odd number of nodes

The logic used in the Source Code:

Here Idea is Very simple:

Step 1: We have to Take two references/pointers(slowReference  & fastReference) , Initially both slowReference and fastReference are pointing to head of Linked List

Step 2: Traverse slowReference one Node and fastReference two Nodes in every iteration so that when fastReference reaches the end of the Linked List then slowReference will reach the middle of the list.

Below is the Complete Source code:

Output Of this Program:

ListList 1::
10->20->30->40->null
Middle Element:30
———————————–
ListList 2::
5->10->15->20->25->null
Middle Element:15

You May Also Like:

 

That’s all about the How to find the middle node in a Singly Linked List 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 *