04-leetcode-回文链表
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2 输出: false
示例 2:
输入: 1->2->2->1 输出: true
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def isPalindrome(self, head: ListNode) -> bool: """要完成回文链表,首先第一步找到中间点(采取快慢指针查找) 第二步,将查找的中间点后的链表反转 第三步,对比两个链表的值""" #快慢指针 slow,fast = head,head #回文最起码的条件 if not head or not head.next: return True #找到中间点 while fast.next and fast.next.next: slow,fast = slow.next,fast.next.next cur = slow.next #另一半链表头起点 last = None #反转链表 while cur: before = cur.next #防止next断裂 cur.next = last last = cur cur = before #对比两个链表的值 while last: if last.val != head.val: return False last,head = last.next,head.next return True