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#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

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;
}
static boolean 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;
}
bool isPalindrome(ListNode* head) {
    ListNode *slow = head, *fast = head;
    while (fast && fast->next) {
        slow = slow->next; fast = fast->next->next;
    }
    ListNode* second = reverseList(slow);
    ListNode *p1 = head, *p2 = second;
    while (p2) {
        if (p1->val != p2->val) return false;
        p1 = p1->next; p2 = p2->next;
    }
    return true;
}
def is_palindrome(head: ListNode | None) -> bool:
    slow = fast = head
    while fast and fast.next:
        slow = slow.next; fast = fast.next.next
    second = reverse(slow)
    p1, p2 = head, second
    while p2:
        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.