【LeetCode】【Python】Linked List Cycle

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

Follow up:

Can you solve it without using extra space?


思路:笨办法是每一个节点再开辟一个属性存放是否訪问过,这样遍历一遍就可以知道是否有环。但为了不添加额外的空间。能够设置两个指针。一个一次走一步,还有一个一次走两步,假设有环则两个指针一定会再次相遇。反之则不会。


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # @param head, a ListNode
    # @return a boolea
    def hasCycle(self, head):
        if head is None:
            return False
        p1 = head
        p2 = head
        while True:
            if p1.next is not None:
                p1=p1.next.next
                p2=p2.next
                if p1 is None or p2 is None:
                    return False
                elif p1 == p2:
                    return True
            else:
                return False
        return False


原文地址:https://www.cnblogs.com/lcchuguo/p/5216884.html