美文网首页
06_环形链表

06_环形链表

作者: butters001 | 来源:发表于2019-10-31 16:17 被阅读0次
    # 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
            """
            if not head:
                return False
    
            cur1 = cur2 = head
            while cur2 and cur2.next:
                cur1 = cur1.next
                cur2 = cur2.next.next
                if cur1 == cur2:
                    return True
            return False
    
    
    # leetcode 上最优解 思路一样 快慢指针 上下两个while的条件都对
    class Solution2(object):
        def hasCycle(self, head):
            """
            :type head: ListNode
            :rtype: bool
            """
            if head is None:
                return head
            fast = head
            slow = head
            while fast.next and fast.next.next:
                fast = fast.next.next
                slow = slow.next
                if fast.val == slow.val:
                    return True
            return False
    
    

    相关文章

      网友评论

          本文标题:06_环形链表

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