Description: Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next
pointer. Internally, pos
is used to denote the index of the node that tail's next
pointer is connected to. Note that pos
is not passed as a parameter. Notice that you should not modify the linked list.
Link:https://leetcode.com/problems/linked-list-cycle-ii/
思路: 141 Linked List Cycle只要求返回True or False, 这个要返回那个再次出现的节点,如果没有则返回None. 把出现过的节点放在set()中,一旦node.next出现在已经遍历过的点中,就返回这个节点。
# 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 not head: return None if not head.next: return None p = head nodes = set() while p: nodes.add(p) if p.next in nodes: return p.next p = p.next return None
日期: 2020-11-26 今天的太阳也很暖