Find the middle of a given linked list

Posted by N.K. Chauhan on Mar 31, 2024

Given the reference (pointer) to the head node of a linked list, the task is to find the middle node of it.

If there are two middle nodes(in case, when "n" is even), print the second middle element.

Input: 1->2->3->4->5->6->null
Output: 4

Input: 1->2->3->4->5->null
Output: 3


Solutions

Method 1: Using two pointers

Traverse linked list using two-pointers - "slow" and "fast".

Move the "slow" pointer by one node and the other "fast" pointer by two nodes.

When the fast pointer reaches the end, the slow pointer will reach the middle of the linked list.

Complexity

The time complexity of this solution is O(n) and space complexity is O(1).

Related


Remove duplicates from an unsorted linked list

Reverse a linked list (Recursion, Iterative, Using Stack, Using Array)

Add two numbers represented by linked lists

Remove duplicates from an sorted linked list

Delete a loop in a linked list (Floyd Cycle)

Detect a loop in a linked list (Floyd Cycle, Map, node modification)

Add 1 to a number represented as a linked list