leetcode-回文链表

234. 回文链表

在此对比的值,不是节点

# 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: Optional[ListNode]) -> bool:
        dummy_head = ListNode(next=head)
        cur = dummy_head.next
        val = []
        while cur:
            val.append(cur.val)
            cur = cur.next
        return val==val[::-1]

使用快慢指针法找到链表的中点,将后半部分链表反转,最后比较前半部分和反转后的后半部分是否相同。

# 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: Optional[ListNode]) -> bool:
        if not head or not head.next:
            return True
        dummy_head = ListNode(next=head)
        slow, fast = dummy_head, dummy_head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        
        prev, cur = None, slow.next
        while cur:
            tmp = cur.next
            cur.next = prev
            prev = cur
            cur = tmp
        p1, p2 = dummy_head.next, prev
        while p2:
            if p1.val != p2.val:
                return False
            p1 = p1.next
            p2 = p2.next
        return True

你可能感兴趣的:(leetcode)