lc 环形链表 II

链接:https://leetcode-cn.com/problems/linked-list-cycle-ii/

代码:

# 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
        """
        visited = set()
        node = head
        while node is not None:
            if node in visited:
                return node
            else:
                visited.add(node)
                node = node.next
        return None
        
View Code

思路:判断一个链表是不是环形链表,如果是的话返回 交点,快慢指针,快的走两步,慢的走一步,则若为环形链表,一定会相遇,然后再设置两个指针,一个从头,一个从相遇的位置,则相遇就是交点

posted on 2020-05-25 00:51  FriskyPuppy  阅读(107)  评论(0编辑  收藏  举报

导航