使用语言 Python, 只针对 LC Medium 和 Hard 题, 面向面试刷题 Note: 除非你面前端 (加上 JS) , 否则统一使用 Python 进行刷题
基本操作
classListNode: def__init__(self, val=0, next=None): self.val = val self.next = next
Dummy(哨兵节点)
用于: Merge Lists, Remove Node, 任何可能改变头节点的情况
dummy = ListNode(0) current = dummy
# ... 操作链表 ...
return dummy.next# 返回真正的头节点
快慢指针找倒数
找倒数第 N 个: fast 先走 N 步
# 找倒数第 N 个节点 dummy = ListNode(0, head) slow = fast = dummy
# fast 先走 N 步 for _ inrange(n): fast = fast.next
# 然后一起走,slow 会停在倒数第 N+1 个(方便删除) while fast.next: # 注意是 fast.next slow = slow.next fast = fast.next
# slow.next 就是倒数第 N 个 return slow.next
快慢指针找环
defdetectCycle(head): # 第一步:快慢指针检测环 slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: break else: returnNone# 无环 # 第二步:找环入口 # 关键:从 head 和相遇点同时出发,相遇点就是环入口 slow = head while slow != fast: slow = slow.next fast = fast.next return slow
快慢指针找中点
# 情况1:偶数个节点时,slow 停在中间偏左 # 1 -> 2 -> 3 -> 4,slow 停在 2 slow, fast = head, head while fast and fast.next: slow = slow.next fast = fast.next.next
# 情况2:偶数个节点时,slow 停在中间偏右 # 1 -> 2 -> 3 -> 4,slow 停在 3 slow, fast = head, head.next while fast and fast.next: slow = slow.next fast = fast.next.next
反转链表
prev = None current = head
while current: next_node = current.next# 先存下一个 current.next = prev # 反转指向 prev = current # prev 前进 current = next_node # current 前进
return prev # 新的头
删除节点
# 删除 current 的下一个节点 current.next = current.next.next
删除节点时的边界
# ❌ 错误:删除头节点时会出问题 defdeleteNode(head, val): curr = head while curr.next: if curr.next.val == val: curr.next = curr.next.next return head curr = curr.next return head