Palindrome Linked List
要点:暴力解,找到中点,然后reverse后半段,再从两边向中间比较。
错误点:
- reverse中pre初始为None而不是slow:因为有可能odd或者even,所以从两边向中间可能left.nextright或者leftright。第一种情况要继续判断left和right而第二种不用。为了统一以简化,right的最后为null而不是连到中点。这样可以以right作为条件。slow的位置可能是中点(odd)或者左边最后(even)。也就是和右边相比相同或者多1。所以right先遍历完。
# 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 not head or not head.next: return True
fast = slow = head
while fast.next:
fast=fast.next
if fast.next:
fast=fast.next
slow=slow.next
# reverse
cur = slow.next
pre = None
while cur:
next = cur.next
cur.next = pre
pre = cur
cur = next
while pre:
if head.val != pre.val:
return False
head = head.next
pre = pre.next
return True