# 234. Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
# Solution
Approach 1: Two pointers.
# Code (Python)
Approach 1:
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
if not head or not head.next:
return True
slow, fast = head, head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
return self._have_same_prefix(head, self._reverse_list(slow.next))
def _reverse_list(self, head):
if not head or not head.next:
return head
new_head = self._reverse_list(head.next)
head.next.next = head
head.next = None
return new_head
def _have_same_prefix(self, head1, head2):
node1, node2 = head1, head2
while node1 and node2:
if node1.val != node2.val:
return False
node1, node2 = node1.next, node2.next
return True
# Code (C++)
Approach 1:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode *slow = head;
ListNode *fast = head;
ListNode *slowPrev = NULL;
while (fast && fast->next)
{
fast = fast->next->next; // need to be here before "slow" reverses the link.
ListNode *slowNext = slow->next;
slow->next = slowPrev;
slowPrev = slow;
slow = slowNext;
}
ListNode *p1 = slowPrev;
ListNode *p2 = (fast == NULL) ? slow : slow->next;
while (p1 && p2)
{
if (p1->val != p2->val)
return false;
p1 = p1->next;
p2 = p2->next;
}
return true;
}
};