原题
https://leetcode.com/problems/linked-list-cycle/
解法1
遍历链表, 将已见过的节点放入seen, 如果遇到已见过的节点则返回True, 遍历结束如果没发现重复的节点则返回False.
Time: O(n)
Space: O(1)
代码
# 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
"""
seen = []
while head:
if head in seen:
return True
else:
seen.append(head)
head = head.next
return False
解法2
定义两个指针, fast和slow, fast每次走两步, slow每次走一步, 如果fast和slow指向同一个节点则返回True, 遍历结束则返回False.
Time: O(n/2)
Space: O(1)
代码
# 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
"""
slow, fast = head, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if slow == fast:
return True
return False