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
    
  • 相关阅读:
    第五周学习进度条
    课堂实验4.1(环数组)
    每日站立会议(3)
    每日站立会议(2)
    找水王
    购买一批书的最低价格
    每日站立会议(1)
    NABCD分析
    团队开发博客
    返回一个二维整数数组中的最大子数组之和(环)
  • 原文地址:https://www.cnblogs.com/absolute/p/5690334.html
Copyright © 2011-2022 走看看