回文链表

# 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 @ 2022-02-14 22:09  Chenyi_li  阅读(33)  评论(0)    收藏  举报