【双指针-简单】234. 回文链表(栈、翻转后半链表,递归法后期补充)

本文探讨如何判断一个链表是否为回文结构。提供了两种Python解决方案,包括基本方法和优化方法,后者在O(n)时间复杂度和O(1)空间复杂度下完成。通过链表中点反转后半部分来验证前半部分是否与其相同,从而确定回文状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【题目】
请判断一个链表是否为回文链表。
【示例 1】
输入: 1->2
输出: false
【示例 2】
输入: 1->2->2->1
输出: true
【进阶】
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
【代码】
【Python】
【方法1:普通法】
在这里插入图片描述

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        num=[]
        while head:
            num.append(head.val)
            head=head.next
        return num==num[::-1]

【方法2:进阶法】
空间复杂度:O(1)
在这里插入图片描述

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        if not head or not head.next:
            return True
        cnt=0
        t=head
        while t:
            cnt+=1
            t=t.next
        half1=head
        pos=None
        for i in range(cnt//2):
            pos=head
            head=head.next
        pos.next=None
        if cnt%2:
            head=head.next
        #对后半部分链表逆转
        pre=head
        cur=head.next
        pre.next=None
        while cur:
            post=cur.next
            cur.next=pre
            pre=cur
            cur=post
        while pre and half1:
            if pre.val!=half1.val:
                return False
            pre=pre.next
            half1=half1.next
        return True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值