141. &142 Linked List Cycle

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

Given a linked list, determine if it has a cycle in it.

解题思路:
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution(object):
    def hasCycle(self, head):
        meet = None
        fast = head
        slow = head

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


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)
    head.next.next.next.next.next.next.next = head.next.next

    print(Solution().hasCycle(head))
上一篇 下一篇

猜你喜欢

热点阅读