leetcode 234

为了减少空间的使用和巩固快慢指针的学习,我使用了快慢指针的写法
为了进行对比,可以将链表的后半部分倒序
之后将倒序过的链表与未倒序的前半部分进行对比
如果此链表为奇数个链表,则将中间那个放在前半部分中
则在判断是否完成时以倒序的链表对比完成为准。

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        if head is None:
            return True
        
        first_half_end = self.first_half(head)
        second_half_start = self.reverse(first_half_end.next)

        result = True
        first_position = head
        second_position = second_half_start
        while result and second_position is not None:
            if first_position.val != second_position.val:
                result = False
            first_position = first_position.next
            second_position = second_position.next

        first_half_end.next = self.reverse(second_half_start)
        return result    

    def first_half(self, head):
        fast = head
        slow = head 
        while fast.next is not None and fast.next.next is not None:
            fast = fast.next.next
            slow = slow.next
        return slow
    
    def reverse(self, head):
        pre = None
        cur = head
        while cur is not None:
            node = cur.next
            cur.next = pre
            pre = cur
            cur = node
        return pre
        
©️2020 CSDN 皮肤主题: 1024 设计师:上身试试 返回首页