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
    
  • 相关阅读:
    8-15 globalCompositeOperation阶段练习二
    8-13 canvas专题-阶段练习二(下)
    8-12 canvas专题-阶段练习一(上)
    最长公共字串
    8-23 canvas专题
    8-2 canvas专题-线条样式
    7-81 js课程小结
    7-80 HTML5新增的JS选择器
    VS快捷键教程
    java.text.NumberFormat使用方法
  • 原文地址:https://www.cnblogs.com/absolute/p/5690334.html
Copyright © 2011-2022 走看看