Find the middle of a given linked list

Posted by 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


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

Delete a loop in a linked list (Floyd Cycle)

Add two numbers represented by linked lists

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

Remove duplicates from an unsorted linked list

Remove duplicates from an sorted linked list

Add 1 to a number represented as a linked list