美文网首页
Leetcode-141题:Linked List Cycle

Leetcode-141题:Linked List Cycle

作者: 八刀一闪 | 来源:发表于2018-12-05 22:53 被阅读6次

题目
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(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        l1 = head
        l2 = head
        while l2 is not None:
            if l2.next == l1:
                return True
            elif l2.next is None:
                return False
            l2 = l2.next.next
            l1 = l1.next
        return False

相关文章

网友评论

      本文标题:Leetcode-141题:Linked List Cycle

      本文链接:https://www.haomeiwen.com/subject/vrajmftx.html