141环形链表_Leon

给定一个链表,判断链表中是否有环。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

字典索引法 && 空间复杂度更低的双链表法

class Solution(object):
    def hasCycle(self, head):
        cur = set([])
        while(head is not None):
            if(head in cur):
                return True
            else:
                cur.add(head)
                head = head.next
        return False
            
     


# 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):
        slow = fast = head
        while(True):
            if(slow is None or fast is None):
                return False
            slow = slow.next
            if(fast.next is None):
                return False
            else:
                fast = fast.next
                if(fast.next is None):
                    return False
                else:
                    fast = fast.next
            if(fast == slow):
                return True
                    
               ```
               
            
        
        
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容