题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,就是规定回文链表就是向前和向后读都相同序列的链表,求判断当前链表是否是回文链表。

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def get_mid(self, head):
left, right = head, head
while right and right.next:
left, right = left.next, right.next.next
return left

def reserve_list(self, head):
pre = None
cur = head
while cur:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
return pre

def isPalindrome(self, head: Optional[ListNode]) -> bool:
mid = self.get_mid(head)
mid = self.reserve_list(mid)
while mid:
if head.val == mid.val:
# print(head, mid) # 虽然前一段的最后一个指针没有编辑,但不妨碍答案的检测
head, mid = head.next, mid.next
else:
return False
return True