Kmoon Blog

【算法合集】双指针

约 139 字 1 min

快慢指针

链表判环

slow = head
fast = head
while fast and fast.next:
    slow = slow.next       # 慢走1步
    fast = fast.next.next  # 快走2步
    if slow == fast:
        return True
# 快指针走到末尾,无环
return False

找中点

slow, fast = head, head
while fast and fast.next:
    slow = slow.next
    fast = fast.next.next

迭代是循环一个个接节点,用 dummy 统一处理头节点,避免单独判断表头。

递归依靠节点之间 next 指针拼接,从头到尾不会新建哑节点。

首尾指针

三指针

链表相交

#Algorithms