Skip to content

876. Middle of the Linked List | LeetCode | Python | Solution

Here is the problem link. See the problem explanation first and try to understand the problem.

It’s an easy linked list problem. We have to return the middle node from a linked list.

We don’t have to check the emptiness of the given linked list. We will receive only a non-empty linked list. If there are two middle nodes, we will return the second one.

To solve this problem, we will use two pointer technique. Those are Slow and Fast. In each iteration, The Slow pointer will move one step forward. The other one will move two-step forward. Both will start from the head node.

When the fast pointer reaches the end of the list, the Slow pointer will stop in the middle of the list. After the loop, we will just return the Slow pointer. If there are two middle nodes, the slow pointer will point the second one after the loop.

See the following code and try to understand the solution.

class Solution:
    def middleNode(self, head: ListNode) -> ListNode:
        slow = fast = head
        while fast and
            slow =
            fast =
        return slow

If you submit the code in LeetCode, it will be accepted.

Published inLeetCode

Comments are closed.