Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
用了两种方法,hash table and two pointers
# 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
"""
## Hash table
nodesSeen = set()
while head is not None:
if head in nodesSeen:
return True
else:
nodesSeen.add(head)
head = head.next
return False
## Two pointers
"""
if head is None:
return False
elif head.next is None:
return False
slow = head
fast = head.next
while slow != fast:
if fast == None or fast.next == None:
return False
slow = slow.next
fast = fast.next.next
return True
"""
```python
在这里插入代码片