← Linked Lists

Find Middle of List

Easy
Python
def middle_node(head):
    slow=fast=head
    while fast and fast.next:
        slow=slow.next; fast=fast.next.next
    return slow
Java
public ListNode middleNode(ListNode head){
    ListNode slow=head,fast=head;
    while(fast!=null&&fast.next!=null){
        slow=slow.next; fast=fast.next.next;
    } return slow;
}

Key Insight

Fast/slow pointer. Truthiness vs null checks.

Python → Java Differences

  • None is falsy vs explicit null
  • Fast/slow identical
  • Same complexity
Python
def middle_node(head):
    slow=fast=head
    while fast and fast.next:
        slow=slow.next; fast=fast.next.next
    return slow
Java
public ListNode middleNode(ListNode head){
    ListNode slow=head,fast=head;
    while(fast!=null&&fast.next!=null){
        slow=slow.next; fast=fast.next.next;
    } return slow;
}

Algorithm Steps

1. Fast 2x speed
2. Fast ends -> slow is middle