1)逐个入栈,检查是否有重复元素出现(效率极低)(类似hashmap)
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: stack = [] temp = head while temp: if temp not in stack: stack.append(temp) temp = temp.next else: return True return False
2)双指针,快指针比慢指针多走几步都行,如果相遇则是环形
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: if head: slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False else: return False
原文:https://www.cnblogs.com/cbachen/p/14845465.html