# Leetcode-双指针系列2

mhxin

## 19. 删除链表的倒数第N个节点

``````def removeNthFromEnd(head, n):
if n < 1 or head == None:

# 快指针先往前移动n步
for i in range(n):
p_fast = p_fast.next

# 如果此时fast指针为None, 则要删除的节点为头节点
if p_fast == None:

# 快慢指针同时前进
while p_fast.next != None:
p_fast = p_fast.next
p_slow = p_slow.next

p_slow.next = p_slow.next.next

## 141. 环形链表

``````def hasCycle(head):
return False

dicts = {}
return True

return False``````

``````def hasCycle(head):
return False

while p1 != p2:

p1 = p1.next
if not p2 or not p2.next:
return False
p2 = p2.next.next

return True``````

## 142. 环形链表 II

``````def detectCycle(head):
return None
dicts = {}

while p:
if p in dicts:
return p
else:
dicts[p] = 0
p = p.next

return None``````

p_start到p_entrance之间的距离为F, p_entrance到p_inter之间的距离为a, p_inter到p_entrance之间的距离为b.

\$2(F+a) = (F+a+b + a) + 1\$

\$F=b+1\$

``````def detectCycle(head):
return None
#设置快慢指针, 快指针是从第二个节点出发

# has_cycle =
inter_node = None

# 快指针和慢指针同时出发
while fast and fast.next:
# 当快指针和慢指针指向同一位置时, 退出循环
if fast == slow:
inter_node = fast
break
fast = fast.next.next
slow = slow.next

# 如果inter_node为None, 说明无环
if not inter_node:
return None

slow = inter_node.next

while fast != slow:
fast = fast.next
slow = slow.next

return slow``````

• 设置快指针(每次走2步)和慢指针(每次走1步), 同时出发, 如果最后快指针和慢指针指向同一位置, 说明有环.
• 直至相遇, 返回相遇节点.

## 160. 相交链表

``````def getIntersectionNode(headA: ListNode, headB: ListNode):
return None

stacka = []
stackb = []

# 将链表a所有节点入栈
while pa:
stacka.append(pa)
pa = pa.next

# 将链表b所有节点入栈
while pb:
stackb.append(pb)
pb = pb.next

res = None
pa = stacka.pop()
pb = stackb.pop()

# 依次出栈
while pa == pb:
res = pa
if not stacka or not stackb:
break
pa = stacka.pop()
pb = stackb.pop()

return res``````

``````def getIntersectionNode(headA: ListNode, headB: ListNode):
return None

dicts = {}
while pa:
dicts[pa] = 1
pa = pa.next

while pb:
# 如果该节点已经在字典中, 则可以直接返回
if pb in dicts:
return pb
pb = pb.next

return None``````

• 如果p1和p2指向的节点相同, 且不为None, 则找到了相交节点

``````def getIntersectionNode(headA: ListNode, headB: ListNode):
return None

while p1 != p2:
p1 = headB if not p1 else p1.next
p2 = headA if not p2 else p2.next

return p1``````

82 声望
12 粉丝
0 条评论