Palindrome linked list
Check whether a list reads the same forwards and backwards by reversing its second half and comparing inward from both ends.
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
- This reuses two earlier patterns back to back: the fast/slow middle finder, then the in-place reversal.
- Stop and return false the moment a pair disagrees — there is no need to keep comparing.
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.