leetcode-234-回文链表

题目描述;

 方法一:O(N) O(1)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        if not head or not head.next:return True
        slow = head
        fast = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        if fast:
            slow = slow.next
        prew = None
        cur = slow
        while cur:
            tmp = cur.next
            cur.next = prew
            prew = cur
            cur = tmp
        p1 = head
        p2 = prew
        while p1 and p2:
            if p1.val!=p2.val:return False
            p1 = p1.next
            p2 = p2.next
        return True
                

猜你喜欢

转载自www.cnblogs.com/oldby/p/11625440.html