Palindrome Linked List — Split, Reverse, Compare
Advertisement
Problem 210 · Palindrome Linked List
Difficulty: Easy · Pattern: Fast/Slow + Reverse
Approach
- Find middle (fast/slow)
- Reverse second half in-place
- Compare first and second halves
- Restore (optional)
Solutions
# Python
def isPalindrome(head):
# Find middle
slow = fast = head
while fast and fast.next:
slow = slow.next; fast = fast.next.next
# Reverse second half
prev, curr = None, slow
while curr:
nxt = curr.next; curr.next = prev; prev = curr; curr = nxt
# Compare
left, right = head, prev
while right:
if left.val != right.val: return False
left = left.next; right = right.next
return True
// Java
public boolean isPalindrome(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next; fast = fast.next.next;
}
ListNode prev = null, curr = slow;
while (curr != null) {
ListNode nxt = curr.next; curr.next = prev; prev = curr; curr = nxt;
}
ListNode left = head, right = prev;
while (right != null) {
if (left.val != right.val) return false;
left = left.next; right = right.next;
}
return true;
}
Complexity
- Time: O(n)
- Space: O(1)
Advertisement