leetcode_234 回文链表

358 阅读1分钟

要求

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。

示例 1:

image.png

输入:head = [1,2,2,1]
输出:true

示例 2:

image.png

输入:head = [1,2]
输出:false

提示:

  • 链表中节点数目在范围[1, 105] 内
  • 0 <= Node.val <= 9  

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

核心代码

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 is None or head.next is None:
            return True
        l = []
        p = head
        while p.next:
            l.append(p.val)
            p = p.next
        l.append(p.val)
        return l == l[::-1]

另一解法

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 is None or head.next is None:
            return True
        if head.next.next is None:
            return head.val == head.next.val
        fast = slow = q = head
        while fast.next and fast.next.next:
            fast = fast.next.next
            slow = slow.next
        def reverse_list(head):
            if head is None:
                return head
            cur = head
            pre = None
            nxt = cur.next
            while nxt:
                cur.next = pre
                pre = cur
                cur = nxt
                nxt = nxt.next
            cur.next = pre
            return cur
        p = reverse_list(slow.next)
        while p.next:
            if p.val != q.val:
                return False
            p = p.next
            q = q.next
        return p.val == q.val

image.png

解题思路:第一种解法:我们使用列表对数据进行存储,然后我们对列表进行反转,反转后的数据和之前的数据看是否相同,相同即是回文链表,否则不是。第二种解法:我们使用快慢指针的方式,当我们的fast运动到最后的时候,我们的slow恰好在中心的位置,我们对slow.next及后面的链表的节点进行反转,然后两个链表进行同时从前向后遍历,比较,最终确定比较结果。