力扣234题(回文链表)

234、判断是否是回文链表

一、递归法,空间复杂度太大,不采用,

但是要会递归是如何进行的,恶心死我了

https://leetcode-cn.com/problems/palindrome-linked-list/solution/hui-wen-lian-biao-by-leetcode-solution/

看不懂官方的快慢指针

二、快慢指针

基本思想:

将链表后半部分反转,然后将前半部分和后半部分进行比较。

比较完后将链表恢复原样

具体实现:

1、通过“双指针技巧”中的快、慢指针来找到链表的中点

慢指针一次走一步,快指针一次走两步

慢指针最后在的地方就是链表的中点

2、反转后半部分链表时

分奇偶情况。

如果fast没有指向null,说明链表长度是奇数,slow还要再往前一步

3、从slow开始反转后面的链表

返回反转之后的头结点

4、开始比较

代码:

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        
        if head is None:
            return True

        # 找到slow并反转后半部分链表
        second_half_start = self.reverse_list(self.end_of_first_half(head))

        # 判断是否回文
        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

        # 还原链表并返回结果
        self.reverse_list(second_half_start)
        return result    

    def end_of_first_half(self, head):
        fast = head
        slow = head
        while fast is not None and fast.next is not None:
            fast = fast.next.next
            slow = slow.next
        if fast is not None:
            return slow.next
        else:
            return slow

    def reverse_list(self, head):
        previous = None
        current = head
        while current is not None:
            next_node = current.next
            current.next = previous
            previous = current
            current = next_node
        return previous
原文地址:https://www.cnblogs.com/zhaojiayu/p/14495696.html