例: 1->2->3->2->1
1.先用双指针找到中点上界。
即:找到第四个节点 2
2.反转后半个链表
即:1->2->3->1->2
3.判断前后半段链表是否相等,如果是奇数个则不管中间值
即判断 1,2 == 1,2
注意:
# 双节点法时:
1.双节点找中间节点时的条件是 while fast and fast.next,为什么不需要fast.next.next呢。 这是因为访问fast.next.next,存在fast.next即可,因为node存在默认的next: node.next = None
2.奇数节点时需要 slow = slow.next。理由如下
1->2->3->2->1
fast 1 1 1
slow 1 1 1
# 后半段链表反转时:
1->2->3->2->1->None
1->2->3 None <- 2 <- 1 <- None
3. 注意经过最后一步的变化后,preNext对应1,而不是想当然的curNode,此时curNode对应右边的None
代码:
# 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:
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
# 如果是奇数,则取上界 fast=5 slow=3 -> slow = 4
# 如果是偶数,fast = None(7) slow = 4 已经是上界了
if fast:
slow = slow.next
preNext = None
curNode = slow
while curNode:
curNext = curNode.next
curNode.next = preNext
preNext = curNode
curNode = curNext
while preNext and head:
if preNext.val != head.val:
return False
preNext = preNext.next
head = head.next
return True