142 Linked List Cycle II
返回循环开始的节点: 使用快慢指针。
Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
slow, fast = head, head
while True:
if fast is None:
return None
if fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
else:
return None
if fast == slow:
fast = head
while fast != slow:
fast = fast.next
slow = slow.next
return fast
Java
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head, fast = head;
while(true){
if(fast == null){
return null;
}
if (fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
else{
return null;
}
if (fast == slow){
fast = head;
while(fast != slow){
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
}
}