142. 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.
- 这 同样是一道链表题,是上一个题的延伸
- 思路可以同上,只需返回链表中第一个重复的链表的位置
# 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
"""
node = head
res = set()
while node is not None:
if node in res:
return node
else:
res.add(node)
node = node.next
return None