/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */
classSolution { publicbooleanhasCycle(ListNode head) {// Set Set<ListNode> nodesSeen = newHashSet<>(); while (head != null) { if (nodesSeen.contains(head)) { returntrue; } else { nodesSeen.add(head); } head = head.next; } returnfalse; } publicbooleanhasCycle(ListNode head) {// 标兵 if (head == null || head.next == null) { returnfalse; } ListNodeslow= head; ListNodefast= head.next; while (slow != fast) { if (fast == null || fast.next == null) { returnfalse; } slow = slow.next; fast = fast.next.next; } returntrue; } }
下面是Python的代码:
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defhasCycle(self, head): # Set nodeset = set() while head: if head in nodeset: returnTrue else: nodeset.add(head) head = head.next returnFalse
defhasCycle(self, head): # 标兵 fast = slow = head while slow and fast and fast.next: slow = slow.next fast = fast.next.next if slow is fast: returnTrue returnFalse