python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
a,b = headA,headB
while a is not b:
a = a.next if a else headB
b = b.next if b else headA
return a
本质:交换跑道,消除长度差
易错点及注意事项:
① 为什么不相交也能正常结束?各走 m+n 步后同时变成 None,a is not b 不成立;
② 比较链表节点时,必须用 is 比较节点对象,不能比 val;
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode | None) -> ListNode | None:
prev,cur = None,head
while cur:
// 保存下一个节点
nxt = cur.next
// 反转当前节点指针
cur.next = prev
// 前移 prev 指针
prev = cur
// 前移 cur 指针
cur = nxt
return prev
易错点及注意事项:
① 最终返回结果为 prev 而非 head,因为反转后此时 head 已是某个尾节点;
② 四行循环体顺序不能乱,先存 nxt 是第一步;
python
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
# 1. 快慢指针找中点(偶数长度时 slow 停在中间偏右)
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# 2. 反转后半段(从 slow 开始)
prev, cur = None, slow
while cur:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
# 3. 从两端向中间比对,以后半段(较短或等长)为准
first, second = head, prev
while second:
if first.val != second.val:
return False
first = first.next
second = second.next
return True
**口诀:**找中点 + 反转 + 双指针比对
易错点及注意事项:
① 第三步 "比对" 时,循环条件用 while second,反转出的后半段一定不长于前半段,走完即可判定结束;
② 追问 "要求不修改链表应当如何处理?比对完再将后半段反转回去接上;
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow=fast=head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow=fast=head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
p=head
while p is not slow:
p = p.next
slow = slow.next
return p
return None