142. &141 Linked List Cycle II

2018-03-06  本文已影响0人  Jonddy
题目要求:

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up :
Can you solve it without using extra space?

解题思路:
代码:
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
        """
        fast = head
        slow = head
        meet = None

        while fast:
            fast = fast.next
            slow = slow.next
            if fast:
                fast = fast.next
            if fast == slow:
                meet = fast
                break
        if meet == None:
            return None

        while head and meet:
            if head == meet:
                return True
            head = head.next
            meet = meet.next
        return None

if __name__ == "__main__":
    head, head.next, head.next.next = ListNode(1), ListNode(2), ListNode(3)
    head.next.next.next, head.next.next.next.next = ListNode(3), ListNode(4)
    head.next.next.next.next.next, head.next.next.next.next.next.next = ListNode(4), ListNode(5)
    

    print(Solution().detectCycle(head))

上一篇下一篇

猜你喜欢

热点阅读