力扣回文链表

力扣回文链表

1.要求

请判断一个链表是否为回文链表。
示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

2.思想及代码

思想:本来想再用一个其他的字符串(或者链表)分别将其中的元素储存起来反转后再遍历比较一遍,但是它要求的是O(1)的空间复杂度。所以利用快慢指针找到中间位置。然后再将其后半部分倒序,最后再比较它倒序后的后半部分链表和前半部分的链表,如果不同就不是回文链表,反之为回文链表

class Solution:
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        #快  慢指针
        if head==None or head.next==None  :
            return True
        fast=head
        low=head
        while fast and fast.next:
            low=low.next
            fast=fast.next.next
        #反转链表后半段
        low=self.reverseList(low)
        while low:
            if head.val!=low.val:
                return False
            head=head.next
            low=low.next
        return True
        
    def reverseList(self, head):
        cur1,pre1=head,None
        while cur1!=None:
            cur1.next,pre1,cur1=pre1,cur1,cur1.next       
        return pre1
        

3.问题

在使用*(1) while head:head=head.next 和(2)while head.next:head=head.next时候要清楚此时到底指向的哪一个节点。和最后会遍历到哪个节点结束。比如[1],(1)当前节点有,为真执行下面的语句,但是(2)就不会执行下边的语句。
[1,2],(1)最终head指向None,但是(2)的head 指向2这个节点.。
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41781408/article/details/88984021