zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 61-1

    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
    
  • 相关阅读:
    JavaScript运行机制 Event Loop
    async 函数
    JavaScript Promise 对象
    pc端rest.css
    微信小程序公用样式类
    移动端base.css
    RegExp正则对象匹配规则
    RegExp正则相关方法
    mysql(五)事务
    mysql(四)海量数据优化
  • 原文地址:https://www.cnblogs.com/absolute/p/5690334.html
Copyright © 2011-2022 走看看