876. Middle of the Linked List

#linked-list

Problem

Intuition

Time Complexity

Space Complexity

Solution

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode middleNode(ListNode head) {
        // n -> Number of nodes in linked list
        // Time Complexity: O(n), we need to traverse through all the nodes once
        // Space Complexity: O(1), as we are not creating any extra container to store results
        
        // Initialize two pointers, walker and runner, both pointing to the head of the linked list
        ListNode walker = head;
        ListNode runner = head;

        // Move the runner pointer by two steps and the walker pointer by one step
        // When the runner reaches the end of the list or the second-to-last node, the walker will be at the middle
        while (runner != null && runner.next != null) {
            walker = walker.next;
            runner = runner.next.next;
        }
        
        // Return the middle node (walker)
        return walker;
    }
}

Last updated

Was this helpful?