leetcode determines whether a linked list is a palindrome

Using list inversion and fast and slow pointers, the value is relatively high:
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head is None:
            return True
        fast=slow=head
        while fast!=None and fast.next!=None:
            fast=fast.next.next
            slow=slow.next
        cur=slow
        prev=None
        while slow!=None:
            cur=slow
            slow=slow.next
            cur.next=prev
            prev=cur
        while cur:
            if cur.val!=head.val:
                return False
            cur=cur.next
            head=head.next
        return True
       

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325831473&siteId=291194637