103. 带环链表 II

103. 带环链表 II

中文English

给定一个链表,如果链表中存在环,则返回到链表中环的起始节点,如果没有环,返回null。

样例

样例 1:

输入:null,no cycle
输出:no cycle
解释:
链表为空,所以没有环存在。

样例 2:

输入:-21->10->4->5,tail connects to node index 1
输出:10
解释:
最后一个节点5指向下标为1的节点,也就是10,所以环的入口为10。

挑战

不使用额外的空间

输入测试数据 (每行一个参数)如何理解测试数据?

 hashmap解法

存储访问过的id地址,如果已经访问过,说明该节点刚好是环的起点,返回,否则走到None,最终返回None

"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param head: The first node of linked list.
    @return: The node where the cycle begins. if there is no cycle, return null
    """
    def detectCycle(self, head):
        # write your code here
        #带环的话,说明id地址刚好重复,则返回,否则的话返回null
        
        if not head: return None
        
        hashmap = {}
        while head:
            if (id(head) not in hashmap):
                hashmap[id(head)] = True
            else:
                return head
            
            head = head.next
        
        return None 
原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13461875.html