【leetcode】142. 环形链表 II

leetcode 2019-02-27 1741 字 1068 浏览 点赞

题目描述:
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。

示例:

有环示例:

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


此题与【141. 环形链表】无太大差别,重点关注第三种算法。

第一种:

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        record = set()
        while head:
            if head in record:
                return head
            record.add(head)
            head = head.next
        return None

第二种:

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        while head:
            if not hasattr(head, "visited"):
                head.visited = True
                head = head.next
            else:
                return head
        else:
            return None

第三种:

  • 首先,通过快慢指针判断链表是否循环。也就是快慢指针是否会相遇;
  • 如果相遇,慢指针继续往后走;同时,在链表头处再派出一个指针,这个指针的速度也为1;
  • 当新指针与慢指针相遇时,相遇点为环点。

详情可见:https://blog.csdn.net/xy010902100449/article/details/48995255#commentsedit

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        slow = fast = head
        while fast and fast.next:
            slow, fast = slow.next, fast.next.next
            if slow is fast:
                break
        else:
            return None

        while head != slow:
            head = head.next
            slow = slow.next
        return head


本文由 Guan 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论