234_回文链表

"""
请判断一个链表是否为回文链表。

示例 1:
输入: 1->2
输出: false

示例 2:
输入: 1->2->2->1
输出: true

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
"""

def isPalindrome(head):
    if head is None:
        return True
    prev = None
    tmp = head

    tmp2 = head
    while head:
        head = head.next
        if head is None:
            break

        tmp.next = prev
        prev = tmp
        tmp = head
    tmp.next = prev
    
    while tmp and tmp2:
        if tmp.val != tmp2.val:
            return False
        tmp = tmp.next
        tmp2 = tmp2.next
    return True



def isPalindrome2(head):
    if not head or not head.next:
        return True
    slow = head
    fast = head
    pre = head
    prepre = None
    while fast and fast.next:
        pre = slow
        slow = slow.next
        fast = fast.next.next
        pre.next = prepre
        prepre = pre
    if fast:
        slow = slow.next
    while pre and slow:
        if pre.val != slow.val:
            return False
        pre = pre.next
        slow = slow.next
    return True



©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页