Java: Middle of the Linked List

Thought Process

To find the middle of a linked list, we use the two-pointer technique. We initialize two pointers, slow and fast, both starting at the head of the list. The slow pointer moves one step at a time, while the fast pointer moves two steps at a time. When the fast pointer reaches the end of the list, the slow pointer will be at the middle. This approach ensures that we find the middle node in a single pass through the list.

/**
 * 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) {
        
        ListNode fast = head;
        ListNode slow = head;

        while(fast!=null && fast.next!=null){

            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
}

Code Complexity

Time Complexity: O(n)

The algorithm iterates through the linked list once, where 'n' is the number of nodes.

Space Complexity: O(1)

The algorithm uses a constant amount of extra space, regardless of the input size.

Code copied!