/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { * val = x; * next = null; * } * } */
while (head != null) { head = head.next; if (head == null) returnfalse; if (hashSet.Contains(head)) returntrue; hashSet.Add(head); } returnfalse; } }
Python 语言
执行结果:通过
执行用时:88 ms, 在所有 Python3 提交中击败了 16.80% 的用户
内存消耗:16.9 MB, 在所有 Python3 提交中击败了 7.04% 的用户
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defhasCycle(self, head: ListNode) -> bool: hashset = set() hashset.add(head) while head isnotNone: head = head.next if head isNone: returnFalse if head in hashset: returnTrue hashset.add(head) returnFalse
第二种:利用双指针的方式
状态:通过
执行用时: 112 ms, 在所有 C# 提交中击败了 98.43% 的用户
内存消耗: 24.9 MB, 在所有 C# 提交中击败了 5.13% 的用户
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { * val = x; * next = null; * } * } */ publicclassSolution { publicboolHasCycle(ListNode head){ ListNode fast = head; ListNode slow = head;
while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (fast == slow) returntrue; } returnfalse; } }
Python 语言
执行结果:通过
执行用时:56 ms, 在所有 Python3 提交中击败了 60.97% 的用户
内存消耗:16.6 MB, 在所有 Python3 提交中击败了 11.81% 的用户
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defhasCycle(self, head: ListNode) -> bool: fast = head slow = head while fast isnotNoneand fast.next isnotNone: fast = fast.next.next slow = slow.next if fast == slow: returnTrue returnFalse