Given the head of a singly linked list, return true if it is a palindrome or false otherwise.
Example 1:
Input: head = [1,2,2,1]
Output: true
Example 2:
Input: head = [1,2]
Output: false
Constraints:
The number of nodes in the list is in the range [1, 105].
0 <= Node.val <= 9
Follow up: Could you do it in O(n) time and O(1) space?
Solutions
Solution 1: Fast and Slow Pointers
We can use fast and slow pointers to find the middle of the linked list, then reverse the right half of the list. After that, we traverse both halves simultaneously, checking if the corresponding node values are equal. If any pair of values is unequal, it's not a palindrome linked list; otherwise, it is a palindrome linked list.
The time complexity is \(O(n)\), where \(n\) is the length of the linked list. The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 91011121314151617181920
# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclassSolution:defisPalindrome(self,head:Optional[ListNode])->bool:slow,fast=head,head.nextwhilefastandfast.next:slow,fast=slow.next,fast.next.nextpre,cur=None,slow.nextwhilecur:t=cur.nextcur.next=prepre,cur=cur,twhilepre:ifpre.val!=head.val:returnFalsepre,head=pre.next,head.nextreturnTrue
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcisPalindrome(head*ListNode)bool{slow,fast:=head,head.Nextforfast!=nil&&fast.Next!=nil{slow,fast=slow.Next,fast.Next.Next}varpre*ListNodecur:=slow.Nextforcur!=nil{t:=cur.Nextcur.Next=prepre=curcur=t}forpre!=nil{ifpre.Val!=head.Val{returnfalse}pre,head=pre.Next,head.Next}returntrue}