题解
思路
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
### 0101 快慢指针 + 链表反转(76 ms,24.6 MB)
def half(self, head):
slow = fast = head
# 注意:这里是快指针fast的下一个节点next 和 下下个节点next.next非空!
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
return slow
def reverse(self, head):
prev, cur = None, head
while cur:
node = cur.next
cur.next, prev = prev, cur
cur = node
return prev
def isPalindrome(self, head: ListNode) -> bool:
if not head: return True
link_list1 = head
# 找到前半部分链表的尾节点
half_start = self.half(head)
# 反转后半部分链表
link_list2 = self.reverse(half_start.next)
# 判断是否回文
while link_list2:
if link_list1.val != link_list2.val: return False
link_list1, link_list2 = link_list1.next, link_list2.next
# 还原链表(非必须!)
# half_start.next = self.reverse(link_list2)
return True
### 0101 辅助列表(80 ms,24.8 MB)
def isPalindrome(self, head: ListNode) -> bool:
if not head: return True
aux_ls, node = [], head
while node:
aux_ls.append(node.val)
node = node.next
return aux_ls == aux_ls[::-1]
- 二刷(0213)
# 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: ListNode) -> bool:
def half(node):
slow = fast = node
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
return slow
def reverse(node):
pre, cur = None, node
while cur:
pre, cur.next, cur = cur, pre, cur.next
return pre
if not head: return True
ln1 = head
ln2 = half(head)
ln2_re = reverse(ln2.next)
while ln2_re:
if ln1.val != ln2_re.val: return False
ln1 = ln1.next
ln2_re = ln2_re.next
return True