【Python刷题】回文链表

文章介绍了如何通过定义两个指针slow和fast遍历链表,将其分为两部分并反转后半部分,然后逐个比较节点值来判断链表是否为回文。
摘要由CSDN通过智能技术生成

问题描述

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
在这里插入图片描述

解决办法

在这里插入图片描述

在这里插入图片描述

  • 定义两个指针 slow 和 fast,只要fast 向后的两个节点存在,那么,slow 每次向后移动一个节点,fast 每次向后移动两个节点。
  • 最终移动完成后会将链表分为两部分,当链表的节点数为偶数时,slow 指向前半个链表的最后一个节点;当链表节点数为奇数时,slow 指向中间节点。fast 则指向后半个链表的最后一个节点。
def half(self,head):
        slow,fast = head,head
        while fast.next is not None and fast.next.next is not None:
            slow=slow.next
            fast=fast.next.next
        return slow
  • 将后半段链表进行反转,即得到以 fast 为头结点的新链表
def reverse(self,head):
        pre=None
        cur=head
        while cur is not None:
            tmp=cur.next
            cur.next=pre
            pre=cur
            cur=tmp
        return pre
  • 最后对前半段链表和后半段链表进行比较,若相等,则为回文,返回 True;若不等,则返回 False。

完整代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        if head is None:
            return True

        pre_half=self.half(head)
        sec_half=self.reverse(pre_half.next)

        result=True

        first=head
        second=sec_half

        while result and second is not None:
            if first.val != second.val:
                return False
            first=first.next
            second=second.next
        return result 
                
    def half(self,head):
        slow,fast = head,head
        while fast.next is not None and fast.next.next is not None:
            slow=slow.next
            fast=fast.next.next
        return slow

    def reverse(self,head):
        pre=None
        cur=head
        while cur is not None:
            tmp=cur.next
            cur.next=pre
            pre=cur
            cur=tmp
        return pre

       

测试结果:
在这里插入图片描述

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值