Linked List Cycle

快慢指针判环,最主要是注意一个节点的情况

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head or not head.next:
            return False

        slow, fast = head, head.next
        while fast and fast.next and slow != fast:
            slow = slow.next
            fast = fast.next.next
        return slow == fast

Linked List Cycle II

如果快慢指针从头结点出发,最后相遇的那个结点到环开始位置的距离和链表头结点到环起点的距离是刚好一样的,注意一些边界判断就好

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        slow, fast = head, head
        if not head or not head.next:
            return None

        slow = slow.next
        fast = fast.next.next

        while fast and fast.next and slow != fast:
            slow = slow.next
            fast = fast.next.next

        if not fast or not fast.next:
            return None

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

        return cur

results matching ""

    No results matching ""