imashutosh51

Palindrome Linked List

Apr 23rd, 2026
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.78 KB | None | 0 0
  1. class Solution:
  2.     def isPalindrome(self, head: Optional[ListNode]) -> bool:
  3.         # Step 1: Find middle
  4.         slow = fast = head
  5.         while fast and fast.next:
  6.             slow = slow.next
  7.             fast = fast.next.next
  8.        
  9.         # Step 2: Skip middle if odd
  10.         if fast:
  11.             slow = slow.next
  12.        
  13.         # Step 3: Reverse second half
  14.         prev = None
  15.         while slow:
  16.             nxt = slow.next
  17.             slow.next = prev
  18.             prev = slow
  19.             slow = nxt
  20.        
  21.         # Step 4: Compare
  22.         left = head
  23.         right = prev
  24.         while right:
  25.             if left.val != right.val:
  26.                 return False
  27.             left = left.next
  28.             right = right.next
  29.        
  30.         return True
Advertisement
Add Comment
Please, Sign In to add comment