Palindrome linked list

Check whether a list reads the same forwards and backwards by reversing its second half and comparing inward from both ends.

Time O(n)Space O(1)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

Find the middle with slow and fast pointers, reverse the list from the middle to the end in place, then walk a pointer in from each end comparing values. If every pair matches before the reversed half runs out, the list is a palindrome.

Code

public static bool IsPalindrome(ListNode head) {
    ListNode slow = head, fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next; fast = fast.next.next;
    }
    ListNode second = Reverse(slow);
    ListNode p1 = head, p2 = second;
    while (p2 != null) {
        if (p1.val != p2.val) return false;
        p1 = p1.next; p2 = p2.next;
    }
    return true;
}

Tips

In the .NET library

This check mutates the list (the second half ends up reversed) while it runs. Production code usually reverses it back afterwards so the caller sees the original order.