链表快慢指针系列 Linked List Fast Slow Series
Idea
Middle of linked list
Check cycle in linked list
There is cycle?
- YES.
SLOW
andFAST
must meet becauseFAST
is one step faster thanSLOW
. - NO. There is end.
FAST
can not move forward forever.
Find entry point of cycle
Template - Find Entry Point
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
fast = head
slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
while head != slow:
slow = slow.next
head = head.next
return head
return None
876. Middle of the Linked List
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = head
fast = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
return slow
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func middleNode(head *ListNode) *ListNode {
slow := head
fast := head
for fast != nil && fast.Next != nil {
fast = fast.Next.Next
slow = slow.Next
}
return slow
}
141. Linked List Cycle
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func hasCycle(head *ListNode) bool {
slow := head
fast := head
for fast != nil && fast.Next != nil {
fast = fast.Next.Next
slow = slow.Next
if slow == fast {
return true
}
}
return false
}
142. Linked List Cycle II Find entry point of Cycle
Python
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
fast = head
slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
while head != slow:
slow = slow.next
head = head.next
return head
return None
Go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func detectCycle(head *ListNode) *ListNode {
slow := head
fast := head
for fast != nil && fast.Next != nil {
fast = fast.Next.Next
slow = slow.Next
if slow == fast {
for head != nil && slow != nil {
if slow == head {
return head
}
slow = slow.Next
head = head.Next
}
return nil
}
}
return nil
}