回文链表

# 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: ListNode) -> bool:
        if head==None or head.next == None:
            return True
        fast = head
        slow = head
        # pre为了得到slow指针前面的位置,从而好做分割
        pre = None

        # 通过快慢指针找到中间位置
        while fast != None and fast.next != None:
            fast = fast.next.next
            pre = slow
            slow = slow.next
        
        # 奇数和偶数处理方案不一致,需要分奇数偶数处理
        if fast == None:
            # 当时偶数时,需要对数列进行对半分
            pre.next = None
            slow = self.reverse(slow)

            while head!=None:
                if head.val != slow.val:
                    return False
                head = head.next
                slow = slow.next
           
        else:
            # 当时奇数时
            pre.next=None
            secNext = slow.next
            slow.next = None

            secNext = self.reverse(secNext)

            while head!=None:
                if head.val!=secNext.val:
                    return False
                head = head.next
                secNext = secNext.next
        return True
    def reverse(self,head:ListNode):
        pre = None

        while head != None:
            next = head.next
            head.next = pre
            pre = head
            head = next

        return pre



        




        # # 递归python超时
        # if head == None or head.next == None:
        #     return True
        # pre = None
        # curr = head

        # while curr.next!=None:
        #     pre = curr
        #     curr = curr.next
        
        # if head.val != curr.val:
        #     return False
        
        # # next = head.next
        # # head.next = None

        # pre.next = None

        # return self.isPalindrome(head.next)

        # 赋值数组
        # data = []
        # while head!=None:
        #     data.append(head.val)
        #     head=head.next
        # i = 0
        # j = len(data)-1
        # while i<j:
        #     if data[i]!=data[j]:
        #         return False
        #     i = i+1
        #     j = j-1
        # return True

作者:静默虚空
欢迎任何形式的转载,但请务必注明出处。
限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。

posted @   Chenyi_li  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示