Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
第一种方法是使用set记录每次访问过的节点,若某节点被二次访问,则说明链表中有环。
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
hashset = set()
while head:
if head in hashset:
return True
else:
hashset.add(head)
head = head.next
return False
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
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):
"""
:type head: ListNode
:rtype: bool
"""
# head和head.next不存在
if not head or not head.next:
return False
slow = head
fast = head.next
while fast != slow:
# linkedlist到头了
if not fast or not fast.next:
return False
fast = fast.next.next
slow = slow.next
return True