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
        
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值