https://leetcode.com/problems/linked-list-cycle-ii/
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
To represent a cycle in the given linked list, we use an integer pos
which represents the position (0-indexed) in the linked list where tail connects to. If pos
is -1
, then there is no cycle in the linked list.
Note: Do not modify the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1 Output: tail connects to node index 1 Explanation: There is a cycle in the linked list, where tail connects to the second node.
判断链表是否存在环,如果存在返回环的起点,否则返回空。
使用快慢指针的方法,但是需要一些技巧参考:https://blog.csdn.net/willduan1/article/details/50938210
# 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
"""
if head == None or head.next == None:
return None
sp = head
fp = head
while fp != None and fp.next != None:
sp = sp.next
fp = fp.next.next
if sp == fp:
break
if fp == None or fp.next == None:
return None
fp = head
while sp != fp:
sp = sp.next
fp = fp.next
return sp