【Leetcode链表】回文链表(234)

题目

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

示例 1:

输入: 1->2
输出: false

示例 2:

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

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

解答

两种方法:

  • 遍历链表,用数组存值,再比较。时间复杂度O(n),空间复杂度O(n)
  • 指针法:找到中点,反转中点之后的链表,再比较。时间复杂度O(n),空间复杂度O(1)

通过代码如下:

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


# Time: O(n),Space: O(1)。找到中点,反转中点之后的链表,再比较
class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        if not head or not head.next:
            return True

        # 快指针结束, 慢指针刚好在中间
        slow = fast = head
        while fast.next:
            slow = slow.next
            fast = fast.next.next if fast.next.next else fast.next

        # reserve behind part of link
        p = None
        while slow:
            n = slow.next
            slow.next = p
            p = slow
            slow = n
        # p is END

        # begin compare with head
        while p:
            if head.val != p.val:
                return False
            head = head.next
            p = p.next
        return True
posted @ 2019-11-26 11:48  961897  阅读(138)  评论(0编辑  收藏  举报