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.nextval = []while cur:val.append(cur.val)cur = cur.nextreturn 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 Truedummy_head = ListNode(next=head)slow, fast = dummy_head, dummy_headwhile fast and fast.next:slow = slow.nextfast = fast.next.nextprev, cur = None, slow.nextwhile cur:tmp = cur.nextcur.next = prevprev = curcur = tmpp1, p2 = dummy_head.next, prevwhile p2:if p1.val != p2.val:return Falsep1 = p1.nextp2 = p2.nextreturn True