Find Middle Element of a Linked List – Java Code

In this tutorial, Let’s discuss how to find middle element of a linked list in a single traversal.

Given a singly linked list, write a code to find middle element in a linked list.

For example: Given a linked list, the middle element in this linked list is 8.

15 -> 9 -> 8 -> 5 -> 6 -> NULL

This type of questions are generally asked in an interviews.

There are multiple approaches to solve this problem. In this tutorial, I am going to discuss two approaches through which we can find the middle element of a singly linked list in one pass.

I have also added video tutorial at the end of this post.

Programming video tutorials

How to Find Middle Element of a Linked List?

Method 1: Finding middle element of a linked in two traversal

i) Traverse a linked list and find the length of a linked list.
ii) Once we know the length of a linked list. We can traverse again upto length/2 and print the value of a node present at mid position.

By using this method we can solve this problem in two traversal.

 

Can we do better than that? How do you find the middle element in a singly linked list in one pass?

Yes we can solve this problem in a single traversal. Let’s discuss our second approach.

Check if a linked list is palindrome or not

Sort a linked list of 0s, 1s and 2s

Method 2: Find middle element in linked list in one pass using two pointers.

i) Use two pointer slow and fast. Initialized both the pointers to the head of a linked list.
ii) Move fast pointer by two step and slow pointer by one step in each iteration.
iii) When fast pointer reaches at the end of a linked list, The slow pointer points to the middle element of a linked list.

Programming questions on linked list

Find Middle Element of a Linked List

Find Middle Element of a Linked List

Find Middle Element of a Linked List in a Single Traversal – Java Code

We have already discussed the algorithm for finding middle element in a linked list.

Let’s write it’s java code.

Find Middle Element in a Linked List LeetCode Solution

Let’s discuss the solution of Middle of the Linked List LeetCode Problem.

In this example, We have solved this problem using two pointers in a single pass.

The time complexity is O(n) and it’s space complexity is O(1).

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.