首页 > 代码库 > 【LeetCode】【Python】Linked List Cycle

【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