definsert_at_tail(head, val):
new_node = ListNode(val)ifnot head:return new_node
cur = head
while cur.next:
cur = cur.next
cur.next= new_node
return head
2 删除节点
删除指定值的节点
defdelete_node(head, val):
dummy = ListNode(0)
dummy.next= head
prev, cur = dummy, head
while cur:if cur.val == val:
prev.next= cur.nextbreak
prev, cur = cur, cur.nextreturn dummy.next
3 反转链表
反转整个链表
defreverse_list(head):
prev, cur =None, head
while cur:
next_node = cur.next
cur.next= prev
prev = cur
cur = next_node
return prev # 新的头节点
反转长度为k的链表(k个一组反转链表)
defreverseKGroup(head, k):# 先检查是否有至少 k 个节点
temp, count = head,0while temp and count < k:
temp = temp.next
count +=1# 如果长度不足 k,则直接返回原链表头部if count < k:return head
# 反转 k 个节点
prev, curr =None, head
for _ inrange(k):
next_node = curr.next
curr.next= prev
prev = curr
curr = next_node
# 递归处理后续的部分,并连接
head.next= reverseKGroup(curr, k)return prev # 返回翻转后的新头节点
4 快慢指针
查找中间节点
deffind_middle(head):
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.nextreturn slow
检测链表是否有环
defhas_cycle(head):
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.nextif slow == fast:returnTruereturnFalse
找到环的起点
defdetect_cycle(head):
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.nextif slow == fast:
ptr = head
while ptr != slow:
ptr = ptr.next
slow = slow.nextreturn ptr # 环的起点returnNone
5 其他
合并两个有序链表
defmerge_two_lists(l1, l2):
dummy = ListNode(0)
cur = dummy
while l1 and l2:if l1.val < l2.val:
cur.next, l1 = l1, l1.nextelse:
cur.next, l2 = l2, l2.next
cur = cur.next
cur.next= l1 if l1 else l2
return dummy.next
分割链表
defsplitList(head, size):# 先找到 next_head 的前一个节点
cur = head
for _ inrange(size -1):if cur isNone:break
cur = cur.next# 如果链表长度 <= sizeif cur isNoneor cur.nextisNone:returnNone# 不做任何操作,返回空节点
next_head = cur.next
cur.next=None# 断开 next_head 的前一个节点和 next_head 的连接return next_head
判断两个链表是否相交
defget_intersection_node(headA, headB):ifnot headA ornot headB:returnNone
a, b = headA, headB
while a != b:
a = a.nextif a else headB
b = b.nextif b else headA
return a