Two Pointers

Published by

on

Pseudo Code

// head is the head node of a linked list
public void function(Node head):
    Node slow = head;
    Node fast = head;

    while (fast != null && fast.next != null) { // IMPORTANT!!
        slow = slow.next;
        fast = fast.next.next;
    }
}
  • With 2 different pointers – slow and fast pointer, we can iterate through the whole list
  • Note that we’re moving slow and fast pointer together, but in different speed
  • The reason why we check ‘fast.next’ as well on the if statement is because fast.next.next may return NPE if fast is at the last node.

Practice Problem

class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
}

Leave a comment